Skip to main content

ENCODE_SOURCE

Constant ENCODE_SOURCE 

Source
pub const ENCODE_SOURCE: &str = "// Brrrty\'s JavaScript data worker: the value encoding.\n//\n// Every value either crosses exactly or is refused with what it is. Wire forms:\n//   plain object   {\"$o\": [[key, value], ...]}  (Object.keys order)\n//   undefined      {\"$u\": 1}\n//   array hole     {\"$hole\": 1}\n//   -0, NaN, +-Inf {\"$n\": \"-0\" | \"NaN\" | \"Infinity\" | \"-Infinity\"}\n//   Date           {\"$d\": <ms since 1970>}\n//   function       {\"$f\": <handle>}\n//   refused        {\"$x\": \"<what it is>\"}\n// Strings, booleans, null, finite numbers and arrays are themselves.\n//\n// This file is concatenated ahead of the worker\'s main module, so it has no\n// exports of its own.\n\nimport { types as utilTypes } from \"node:util\";\n\n// How many objects and arrays deep a value may nest. Brrrty\'s templates and\n// filters walk values recursively, so a deeper one is refused, never a crash.\nconst MAX_DEPTH = 1000;\n\nconst LONE_SURROGATE = /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/;\n\n// `String.prototype.isWellFormed` where Node has it (20 and later).\nconst wellFormed =\n  typeof String.prototype.isWellFormed === \"function\"\n    ? (s) => s.isWellFormed()\n    : (s) => !LONE_SURROGATE.test(s);\n\nconst LONE_SURROGATES = new RegExp(LONE_SURROGATE.source, \"g\");\n\n// `s` with each lone surrogate replaced by U+FFFD, so it can cross as\n// JSON text Brrrty reads.\nfunction toWellFormed(s) {\n  return typeof s.toWellFormed === \"function\" ? s.toWellFormed() : s.replace(LONE_SURROGATES, \"\\uFFFD\");\n}\n\nfunction article(word) {\n  // \"a Uint8Array\", \"a URL\", \"an Uncommon\".\n  const vowel = /^[AEIOaeio]/.test(word) || (/^[Uu]/.test(word) && !/^U(int|RL|rl|ni|s)/.test(word));\n  return vowel ? \"an\" : \"a\";\n}\n\n// \"a Map object\", \"a Foo object\", \"an object with a null-less prototype\".\nfunction describeObject(value) {\n  let name;\n  try {\n    const proto = Object.getPrototypeOf(value);\n    const ctor = proto && Object.prototype.hasOwnProperty.call(proto, \"constructor\") ? proto.constructor : undefined;\n    name = typeof ctor === \"function\" && ctor.name ? ctor.name : undefined;\n  } catch {\n    name = undefined;\n  }\n  if (!name) {\n    return \"an object that isn\'t a plain object\";\n  }\n  return `${article(name)} ${name} object`;\n}\n\n// Symbols that change how JavaScript reads an object: printing it, listing\n// it, iterating it.\nconst WELL_KNOWN = new Set(\n  Object.getOwnPropertyNames(Symbol)\n    .map((name) => Symbol[name])\n    .filter((v) => typeof v === \"symbol\"),\n);\n\n// What a template could see on `v` that its enumerable string keys don\'t\n// carry: own non-enumerable string keys (other than an array\'s indexes and\n// `length`) and own well-known symbols. 11ty hands some objects to\n// templates as they are, where these stay readable.\nfunction unseen(v, isArray) {\n  const symbols = Object.getOwnPropertySymbols(v);\n  const names = Object.getOwnPropertyNames(v);\n  // The common case, quickly: every string key enumerable (an array\'s\n  // `length` aside) and no symbols.\n  if (!symbols.length && names.length === Object.keys(v).length + (isArray ? 1 : 0)) return [];\n  const hidden = names.filter((k) => {\n    if (isArray && (k === \"length\" || (String(k >>> 0) === k && (k >>> 0) !== 4294967295))) return false;\n    const d = Object.getOwnPropertyDescriptor(v, k);\n    return d && !d.enumerable;\n  });\n  const known = symbols.filter((s) => WELL_KNOWN.has(s)).map((s) => s.description);\n  return [...hidden, ...known];\n}\n\nfunction pathText(path) {\n  return toWellFormed(pathTextRaw(path));\n}\n\nfunction pathTextRaw(path) {\n  let out = \"data\";\n  for (const part of path) {\n    out += typeof part === \"number\" ? `[${part}]` : /^[A-Za-z_$][\\w$]*$/.test(part) ? `.${part}` : `[${JSON.stringify(part)}]`;\n  }\n  return out;\n}\n\n// Encode `value`. `register(fn)` returns a handle for a function value.\nfunction encodeValue(value, register) {\n  const stack = [];\n  const stackPaths = [];\n  const path = [];\n\n  function encodeString(s) {\n    return wellFormed(s) ? s : { $x: \"a string with a lone surrogate\" };\n  }\n\n  // `shared`: 11ty hands this value to templates as it is rather than\n  // copying its enumerable keys (`getMergedItem` in @11ty/eleventy-utils\n  // keeps arrays, and frozen plain objects, by reference).\n  function enc(v, shared) {\n    switch (typeof v) {\n      case \"undefined\":\n        return { $u: 1 };\n      case \"boolean\":\n        return v;\n      case \"string\":\n        return encodeString(v);\n      case \"number\":\n        if (Object.is(v, -0)) return { $n: \"-0\" };\n        if (Number.isNaN(v)) return { $n: \"NaN\" };\n        if (v === Infinity) return { $n: \"Infinity\" };\n        if (v === -Infinity) return { $n: \"-Infinity\" };\n        return v;\n      case \"bigint\":\n        return { $x: \"a BigInt\" };\n      case \"symbol\":\n        return { $x: \"a Symbol\" };\n      case \"function\":\n        return { $f: register(v) };\n    }\n    if (v === null) return null;\n    // A proxy can answer reads its own properties don\'t hold.\n    if (utilTypes.isProxy(v)) return { $x: \"a Proxy\" };\n    const at = stack.indexOf(v);\n    if (at !== -1) {\n      return { $x: `a circular reference to ${pathText(stackPaths[at])}` };\n    }\n    const proto = Object.getPrototypeOf(v);\n    if (proto === Date.prototype) {\n      const extra = Object.keys(v);\n      if (extra.length) return { $x: `a Date with other properties (${extra.join(\", \")})` };\n      const ms = Date.prototype.getTime.call(v);\n      return Number.isNaN(ms) ? { $x: \"an invalid Date\" } : { $d: ms };\n    }\n    if (stack.length >= MAX_DEPTH) {\n      return { $x: `a value nested more than ${MAX_DEPTH} objects and arrays deep` };\n    }\n    if (Array.isArray(v) && proto === Array.prototype) {\n      // Templates can read a property set on an array (`list.total`).\n      const extra = Object.keys(v).filter((k) => !(String(k >>> 0) === k && (k >>> 0) !== 4294967295));\n      if (extra.length) return { $x: `an array with other properties (${extra.join(\", \")})` };\n      const hidden = unseen(v, true);\n      if (hidden.length) return { $x: `an array with properties Brrrty can\'t list (${hidden.join(\", \")}), which 11ty passes to templates as they are` };\n      stack.push(v);\n      stackPaths.push(path.slice());\n      const out = [];\n      for (let i = 0; i < v.length; i++) {\n        if (!Object.prototype.hasOwnProperty.call(v, i)) {\n          out.push({ $hole: 1 });\n          continue;\n        }\n        path.push(i);\n        out.push(enc(v[i], true));\n        path.pop();\n      }\n      stack.pop();\n      stackPaths.pop();\n      return out;\n    }\n    if (proto === Object.prototype || proto === null) {\n      const byReference = shared || Object.isFrozen(v);\n      if (byReference) {\n        const hidden = unseen(v, false);\n        if (hidden.length) return { $x: `an object with properties Brrrty can\'t list (${hidden.join(\", \")}), which 11ty passes to templates as they are` };\n      }\n      stack.push(v);\n      stackPaths.push(path.slice());\n      const entries = [];\n      for (const key of Object.keys(v)) {\n        path.push(key);\n        let item;\n        if (!wellFormed(key)) {\n          item = { $x: \"a key with a lone surrogate\" };\n        } else {\n          const desc = Object.getOwnPropertyDescriptor(v, key);\n          if (desc && desc.get) {\n            // 11ty reads a getter as many times as it copies the data, so\n            // one that changes between reads has no single value.\n            const first = enc(v[key], byReference);\n            const second = enc(v[key], byReference);\n            item = JSON.stringify(first) === JSON.stringify(second) ? first : { $x: \"a getter that returns a different value each time it is read\" };\n          } else {\n            item = enc(desc ? desc.value : v[key], byReference);\n          }\n        }\n        // A key with a lone surrogate is refused, under a name that can\n        // cross.\n        entries.push([wellFormed(key) ? key : toWellFormed(key), item]);\n        path.pop();\n      }\n      stack.pop();\n      stackPaths.pop();\n      return { $o: entries };\n    }\n    return { $x: describeObject(v) };\n  }\n\n  return enc(value, false);\n}\n";
Expand description

The worker’s value encoding, as JavaScript source.