UNPKG

wrangler

Version:

Command-line interface for all things Cloudflare Workers

1,524 lines (1,514 loc) • 12 MB
'use strict'; var assert50 = require('assert'); var module2 = require('module'); var path3 = require('path'); var fs23 = require('fs'); var os10 = require('os'); var util2 = require('util'); var Url = require('url'); var process7 = require('process'); var tty = require('tty'); var childProcess = require('child_process'); var crypto2 = require('crypto'); var fs12 = require('fs/promises'); var esbuild = require('esbuild'); var miniflare = require('miniflare'); var async_hooks = require('async_hooks'); var console$1 = require('console'); var S = require('readline'); var Stream = require('stream'); var http = require('http'); var https = require('https'); var zlib = require('zlib'); var web = require('stream/web'); var events = require('events'); var buffer = require('buffer'); var net = require('net'); var domain = require('domain'); var consumers = require('stream/consumers'); var string_decoder = require('string_decoder'); var blake3Wasm = require('blake3-wasm'); var promises = require('timers/promises'); var workerd = require('workerd'); function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } function _interopNamespace(e) { if (e && e.__esModule) return e; var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n.default = e; return Object.freeze(n); } var assert50__default = /*#__PURE__*/_interopDefault(assert50); var module2__default = /*#__PURE__*/_interopDefault(module2); var path3__namespace = /*#__PURE__*/_interopNamespace(path3); var fs23__namespace = /*#__PURE__*/_interopNamespace(fs23); var os10__namespace = /*#__PURE__*/_interopNamespace(os10); var util2__namespace = /*#__PURE__*/_interopNamespace(util2); var Url__default = /*#__PURE__*/_interopDefault(Url); var process7__default = /*#__PURE__*/_interopDefault(process7); var tty__default = /*#__PURE__*/_interopDefault(tty); var childProcess__default = /*#__PURE__*/_interopDefault(childProcess); var crypto2__default = /*#__PURE__*/_interopDefault(crypto2); var fs12__default = /*#__PURE__*/_interopDefault(fs12); var esbuild__namespace = /*#__PURE__*/_interopNamespace(esbuild); var async_hooks__namespace = /*#__PURE__*/_interopNamespace(async_hooks); var S__default = /*#__PURE__*/_interopDefault(S); var Stream__namespace = /*#__PURE__*/_interopNamespace(Stream); var http__namespace = /*#__PURE__*/_interopNamespace(http); var https__namespace = /*#__PURE__*/_interopNamespace(https); var zlib__namespace = /*#__PURE__*/_interopNamespace(zlib); var events__default = /*#__PURE__*/_interopDefault(events); var net__default = /*#__PURE__*/_interopDefault(net); var domain__namespace = /*#__PURE__*/_interopNamespace(domain); var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __require = /* @__PURE__ */ ((x7) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x7, { get: (a7, b11) => (typeof require !== "undefined" ? require : a7)[b11] }) : x7)(function(x7) { if (typeof require !== "undefined") return require.apply(this, arguments); throw Error('Dynamic require of "' + x7 + '" is not supported'); }); var __esm = (fn2, res) => function __init() { return fn2 && (res = (0, fn2[__getOwnPropNames(fn2)[0]])(fn2 = 0)), res; }; var __commonJS = (cb2, mod) => function __require3() { return mod || (0, cb2[__getOwnPropNames(cb2)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all3) => { for (var name2 in all3) __defProp(target, name2, { get: all3[name2], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget); var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // import_meta_url.js var import_meta_url; var init_import_meta_url = __esm({ "import_meta_url.js"() { import_meta_url = __require("url").pathToFileURL(__filename); } }); // ../../node_modules/.pnpm/cloudflare@5.2.0_encoding@0.1.13/node_modules/cloudflare/_shims/registry.mjs function setShims(shims, options = { auto: false }) { if (auto) { throw new Error(`you must \`import 'cloudflare/shims/${shims.kind}'\` before importing anything else from cloudflare`); } if (kind) { throw new Error(`can't \`import 'cloudflare/shims/${shims.kind}'\` after \`import 'cloudflare/shims/${kind}'\``); } auto = options.auto; kind = shims.kind; fetch2 = shims.fetch; shims.Request; shims.Response; shims.Headers; FormData2 = shims.FormData; shims.Blob; File2 = shims.File; shims.ReadableStream; getMultipartRequestOptions = shims.getMultipartRequestOptions; getDefaultAgent = shims.getDefaultAgent; fileFromPath = shims.fileFromPath; isFsReadStream = shims.isFsReadStream; } var auto, kind, fetch2, FormData2, File2, getMultipartRequestOptions, getDefaultAgent, fileFromPath, isFsReadStream; var init_registry = __esm({ "../../node_modules/.pnpm/cloudflare@5.2.0_encoding@0.1.13/node_modules/cloudflare/_shims/registry.mjs"() { init_import_meta_url(); auto = false; kind = void 0; fetch2 = void 0; FormData2 = void 0; File2 = void 0; getMultipartRequestOptions = void 0; getDefaultAgent = void 0; fileFromPath = void 0; isFsReadStream = void 0; __name(setShims, "setShims"); } }); // ../../node_modules/.pnpm/cloudflare@5.2.0_encoding@0.1.13/node_modules/cloudflare/_shims/MultipartBody.mjs var MultipartBody; var init_MultipartBody = __esm({ "../../node_modules/.pnpm/cloudflare@5.2.0_encoding@0.1.13/node_modules/cloudflare/_shims/MultipartBody.mjs"() { init_import_meta_url(); MultipartBody = class { static { __name(this, "MultipartBody"); } constructor(body) { this.body = body; } get [Symbol.toStringTag]() { return "MultipartBody"; } }; } }); // ../workers-utils/dist/chunk-LDFBMPMW.mjs var __create2, __defProp2, __getOwnPropDesc2, __getOwnPropNames2, __getProtoOf2, __hasOwnProp2, __name2, __require2, __commonJS2, __export2, __copyProps2, __reExport2, __toESM2, INHERIT_SYMBOL, SERVICE_TAG_PREFIX, ENVIRONMENT_TAG_PREFIX, PATH_TO_DEPLOY_CONFIG, JSON_CONFIG_FORMATS; var init_chunk_LDFBMPMW = __esm({ "../workers-utils/dist/chunk-LDFBMPMW.mjs"() { init_import_meta_url(); __create2 = Object.create; __defProp2 = Object.defineProperty; __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; __getOwnPropNames2 = Object.getOwnPropertyNames; __getProtoOf2 = Object.getPrototypeOf; __hasOwnProp2 = Object.prototype.hasOwnProperty; __name2 = /* @__PURE__ */ __name((target, value) => __defProp2(target, "name", { value, configurable: true }), "__name"); __require2 = /* @__PURE__ */ ((x7) => typeof __require !== "undefined" ? __require : typeof Proxy !== "undefined" ? new Proxy(x7, { get: /* @__PURE__ */ __name((a7, b11) => (typeof __require !== "undefined" ? __require : a7)[b11], "get") }) : x7)(function(x7) { if (typeof __require !== "undefined") return __require.apply(this, arguments); throw Error('Dynamic require of "' + x7 + '" is not supported'); }); __commonJS2 = /* @__PURE__ */ __name((cb2, mod) => /* @__PURE__ */ __name(function __require22() { return mod || (0, cb2[__getOwnPropNames2(cb2)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }, "__require2"), "__commonJS"); __export2 = /* @__PURE__ */ __name((target, all3) => { for (var name2 in all3) __defProp2(target, name2, { get: all3[name2], enumerable: true }); }, "__export"); __copyProps2 = /* @__PURE__ */ __name((to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames2(from)) if (!__hasOwnProp2.call(to, key) && key !== except) __defProp2(to, key, { get: /* @__PURE__ */ __name(() => from[key], "get"), enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable }); } return to; }, "__copyProps"); __reExport2 = /* @__PURE__ */ __name((target, mod, secondTarget) => (__copyProps2(target, mod, "default"), secondTarget && __copyProps2(secondTarget, mod, "default")), "__reExport"); __toESM2 = /* @__PURE__ */ __name((mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target, mod )), "__toESM"); INHERIT_SYMBOL = Symbol.for("inherit_binding"); SERVICE_TAG_PREFIX = "cf:service="; ENVIRONMENT_TAG_PREFIX = "cf:environment="; PATH_TO_DEPLOY_CONFIG = ".wrangler/deploy/config.json"; JSON_CONFIG_FORMATS = ["json", "jsonc"]; } }); function getLocalWorkerdCompatibilityDate({ projectPath = process.cwd() } = {}) { try { const projectRequire = module2__default.default.createRequire( path3__namespace.default.join(projectPath, "package.json") ); const miniflareEntry = projectRequire.resolve("miniflare"); const miniflareRequire = module2__default.default.createRequire(miniflareEntry); const miniflareWorkerd = miniflareRequire("workerd"); const workerdDate = miniflareWorkerd.compatibilityDate; return { date: toSafeCompatibilityDate(new Date(workerdDate)), source: "workerd" }; } catch { } return { date: "2025-09-27", source: "fallback" }; } function toSafeCompatibilityDate(date) { if (date.getTime() > Date.now()) { return formatCompatibilityDate(/* @__PURE__ */ new Date()); } return formatCompatibilityDate(date); } function isCompatDate(str) { return /^\d{4}-\d{2}-\d{2}$/.test(str); } function formatCompatibilityDate(date) { const compatDate = date.toISOString().slice(0, 10); assert50__default.default(isCompatDate(compatDate)); return compatDate; } function assertNever(_value) { } function mapWorkerMetadataBindings(bindings) { return bindings.filter((binding) => binding.type !== "secret_text").reduce((configObj, binding) => { switch (binding.type) { case "plain_text": { configObj.vars = { ...configObj.vars ?? {}, [binding.name]: binding.text }; } break; case "json": { configObj.vars = { ...configObj.vars ?? {}, name: binding.name, json: binding.json }; } break; case "kv_namespace": { configObj.kv_namespaces = [ ...configObj.kv_namespaces ?? [], { id: binding.namespace_id, binding: binding.name } ]; } break; case "durable_object_namespace": { configObj.durable_objects = { bindings: [ ...configObj.durable_objects?.bindings ?? [], { name: binding.name, class_name: binding.class_name, script_name: binding.script_name, environment: binding.environment } ] }; } break; case "d1": { configObj.d1_databases = [ ...configObj.d1_databases ?? [], { binding: binding.name, database_id: binding.id } ]; } break; case "browser": { configObj.browser = { binding: binding.name }; } break; case "ai": { configObj.ai = { binding: binding.name }; } break; case "images": { configObj.images = { binding: binding.name }; } break; case "media": { configObj.media = { binding: binding.name }; } break; case "r2_bucket": { configObj.r2_buckets = [ ...configObj.r2_buckets ?? [], { binding: binding.name, bucket_name: binding.bucket_name, jurisdiction: binding.jurisdiction } ]; } break; case "secrets_store_secret": { configObj.secrets_store_secrets = [ ...configObj.secrets_store_secrets ?? [], { binding: binding.name, store_id: binding.store_id, secret_name: binding.secret_name } ]; } break; case "unsafe_hello_world": { configObj.unsafe_hello_world = [ ...configObj.unsafe_hello_world ?? [], { binding: binding.name, enable_timer: binding.enable_timer } ]; break; } case "service": { configObj.services = [ ...configObj.services ?? [], { binding: binding.name, service: binding.service, environment: binding.environment, entrypoint: binding.entrypoint } ]; } break; case "analytics_engine": { configObj.analytics_engine_datasets = [ ...configObj.analytics_engine_datasets ?? [], { binding: binding.name, dataset: binding.dataset } ]; } break; case "dispatch_namespace": { configObj.dispatch_namespaces = [ ...configObj.dispatch_namespaces ?? [], { binding: binding.name, namespace: binding.namespace, ...binding.outbound && { outbound: { service: binding.outbound.worker.service, environment: binding.outbound.worker.environment, parameters: binding.outbound.params?.map((p7) => p7.name) ?? [] } } } ]; } break; case "logfwdr": { configObj.logfwdr = { bindings: [ ...configObj.logfwdr?.bindings ?? [], { name: binding.name, destination: binding.destination } ] }; } break; case "wasm_module": { configObj.wasm_modules = { ...configObj.wasm_modules ?? {}, [binding.name]: binding.part }; } break; case "text_blob": { configObj.text_blobs = { ...configObj.text_blobs ?? {}, [binding.name]: binding.part }; } break; case "data_blob": { configObj.data_blobs = { ...configObj.data_blobs ?? {}, [binding.name]: binding.part }; } break; case "secret_text": break; case "version_metadata": { { configObj.version_metadata = { binding: binding.name }; } break; } case "send_email": { configObj.send_email = [ ...configObj.send_email ?? [], { name: binding.name, destination_address: binding.destination_address, allowed_destination_addresses: binding.allowed_destination_addresses, allowed_sender_addresses: binding.allowed_sender_addresses } ]; break; } case "queue": configObj.queues ??= { producers: [] }; configObj.queues.producers = [ ...configObj.queues.producers ?? [], { binding: binding.name, queue: binding.queue_name, delivery_delay: binding.delivery_delay } ]; break; case "vectorize": configObj.vectorize = [ ...configObj.vectorize ?? [], { binding: binding.name, index_name: binding.index_name } ]; break; case "hyperdrive": configObj.hyperdrive = [ ...configObj.hyperdrive ?? [], { binding: binding.name, id: binding.id } ]; break; case "mtls_certificate": configObj.mtls_certificates = [ ...configObj.mtls_certificates ?? [], { binding: binding.name, certificate_id: binding.certificate_id } ]; break; case "pipelines": configObj.pipelines = [ ...configObj.pipelines ?? [], { binding: binding.name, pipeline: binding.pipeline } ]; break; case "assets": configObj.assets = { binding: binding.name // Note: we currently don't get all the assets information from the // API, so here we are only able to set the name of the binding // hopefully in the future we can properly fully support the binding }; break; case "inherit": configObj.unsafe = { bindings: [...configObj.unsafe?.bindings ?? [], binding], metadata: configObj.unsafe?.metadata ?? void 0 }; break; case "workflow": { configObj.workflows = [ ...configObj.workflows ?? [], { binding: binding.name, name: binding.workflow_name, class_name: binding.class_name, script_name: binding.script_name } ]; } break; case "worker_loader": { configObj.worker_loaders = [ ...configObj.worker_loaders ?? [], { binding: binding.name } ]; } break; case "ratelimit": { configObj.ratelimits = [ ...configObj.ratelimits ?? [], { name: binding.name, namespace_id: binding.namespace_id, simple: { limit: binding.simple.limit, period: binding.simple.period } } ]; } break; case "vpc_service": { configObj.vpc_services = [ ...configObj.vpc_services ?? [], { binding: binding.name, service_id: binding.service_id } ]; } break; default: { configObj.unsafe = { bindings: [...configObj.unsafe?.bindings ?? [], binding], metadata: configObj.unsafe?.metadata ?? void 0 }; } } return configObj; }, {}); } function convertWorkerToWranglerConfig(config) { const mappedBindings = mapWorkerMetadataBindings(config.bindings); const durableObjectClassNames = config.bindings.filter( (binding) => binding.type === "durable_object_namespace" && binding.script_name === config.name ).map( (durableObject) => durableObject.class_name ); const allRoutes = [ ...config.routes.map((r9) => ({ pattern: r9.pattern, zone_name: r9.zone_name })), ...config.domains.map((c8) => ({ pattern: c8.hostname, zone_name: c8.zone_name, custom_domain: true })) ]; return { name: config.name, main: config.entrypoint, workers_dev: config.subdomain.enabled, preview_urls: config.subdomain.previews_enabled, compatibility_date: config.compatibility_date ?? formatCompatibilityDate(/* @__PURE__ */ new Date()), compatibility_flags: config.compatibility_flags, ...allRoutes.length ? { routes: allRoutes } : {}, placement: config.placement?.mode === "smart" ? { mode: "smart" } : void 0, limits: config.limits, ...durableObjectClassNames.length && config.migration_tag ? { migrations: [ { tag: config.migration_tag, new_classes: durableObjectClassNames } ] } : {}, ...config.schedules.length ? { triggers: { crons: config.schedules.map((scheduled) => scheduled.cron) } } : {}, tail_consumers: config.tail_consumers ?? void 0, observability: config.observability, ...mappedBindings }; } function constructWranglerConfig(workerOrWorkers) { let workers; if (Array.isArray(workerOrWorkers)) { workers = workerOrWorkers; } else { workers = [workerOrWorkers]; } const topLevelEnv = workers.find( (w7) => !w7.tags?.some((t12) => t12.startsWith(ENVIRONMENT_TAG_PREFIX)) ); const workerName = topLevelEnv?.name ?? workers[0].name; const entrypoint = topLevelEnv?.entrypoint ?? workers[0].entrypoint; let combinedConfig; if (topLevelEnv) { combinedConfig = convertWorkerToWranglerConfig(topLevelEnv); } else { combinedConfig = { name: workerName, main: entrypoint }; } for (const env6 of workers) { const serviceTag = env6.tags?.find( (t12) => t12 === `${SERVICE_TAG_PREFIX}${workerName}` ); const envTag = env6.tags?.find((t12) => t12.startsWith(ENVIRONMENT_TAG_PREFIX)); if (serviceTag !== `${SERVICE_TAG_PREFIX}${workerName}` || envTag === void 0) { continue; } const [_5, envName] = envTag.split("="); combinedConfig.env ??= {}; combinedConfig.env[envName] = convertWorkerToWranglerConfig(env6); } return combinedConfig; } var init_chunk_4233U5MA = __esm({ "../workers-utils/dist/chunk-4233U5MA.mjs"() { init_import_meta_url(); init_chunk_LDFBMPMW(); __name(getLocalWorkerdCompatibilityDate, "getLocalWorkerdCompatibilityDate"); __name2(getLocalWorkerdCompatibilityDate, "getLocalWorkerdCompatibilityDate"); __name(toSafeCompatibilityDate, "toSafeCompatibilityDate"); __name2(toSafeCompatibilityDate, "toSafeCompatibilityDate"); __name(isCompatDate, "isCompatDate"); __name2(isCompatDate, "isCompatDate"); __name(formatCompatibilityDate, "formatCompatibilityDate"); __name2(formatCompatibilityDate, "formatCompatibilityDate"); __name(assertNever, "assertNever"); __name2(assertNever, "assertNever"); __name(mapWorkerMetadataBindings, "mapWorkerMetadataBindings"); __name2(mapWorkerMetadataBindings, "mapWorkerMetadataBindings"); __name(convertWorkerToWranglerConfig, "convertWorkerToWranglerConfig"); __name2(convertWorkerToWranglerConfig, "convertWorkerToWranglerConfig"); __name(constructWranglerConfig, "constructWranglerConfig"); __name2(constructWranglerConfig, "constructWranglerConfig"); } }); function createFatalError(message, isJson, code, telemetryMessage) { if (isJson) { return new JsonFriendlyFatalError( JSON.stringify(message), code, telemetryMessage ); } else { return new FatalError(`${message}`, code, telemetryMessage); } } function createScanner(text, ignoreTrivia = false) { const len = text.length; let pos = 0, value = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0; function scanHexDigits(count, exact) { let digits2 = 0; let value2 = 0; while (digits2 < count || !exact) { let ch2 = text.charCodeAt(pos); if (ch2 >= 48 && ch2 <= 57) { value2 = value2 * 16 + ch2 - 48; } else if (ch2 >= 65 && ch2 <= 70) { value2 = value2 * 16 + ch2 - 65 + 10; } else if (ch2 >= 97 && ch2 <= 102) { value2 = value2 * 16 + ch2 - 97 + 10; } else { break; } pos++; digits2++; } if (digits2 < count) { value2 = -1; } return value2; } __name(scanHexDigits, "scanHexDigits"); __name2(scanHexDigits, "scanHexDigits"); function setPosition(newPosition) { pos = newPosition; value = ""; tokenOffset = 0; token = 16; scanError = 0; } __name(setPosition, "setPosition"); __name2(setPosition, "setPosition"); function scanNumber() { let start = pos; if (text.charCodeAt(pos) === 48) { pos++; } else { pos++; while (pos < text.length && isDigit(text.charCodeAt(pos))) { pos++; } } if (pos < text.length && text.charCodeAt(pos) === 46) { pos++; if (pos < text.length && isDigit(text.charCodeAt(pos))) { pos++; while (pos < text.length && isDigit(text.charCodeAt(pos))) { pos++; } } else { scanError = 3; return text.substring(start, pos); } } let end = pos; if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) { pos++; if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) { pos++; } if (pos < text.length && isDigit(text.charCodeAt(pos))) { pos++; while (pos < text.length && isDigit(text.charCodeAt(pos))) { pos++; } end = pos; } else { scanError = 3; } } return text.substring(start, end); } __name(scanNumber, "scanNumber"); __name2(scanNumber, "scanNumber"); function scanString() { let result = "", start = pos; while (true) { if (pos >= len) { result += text.substring(start, pos); scanError = 2; break; } const ch2 = text.charCodeAt(pos); if (ch2 === 34) { result += text.substring(start, pos); pos++; break; } if (ch2 === 92) { result += text.substring(start, pos); pos++; if (pos >= len) { scanError = 2; break; } const ch22 = text.charCodeAt(pos++); switch (ch22) { case 34: result += '"'; break; case 92: result += "\\"; break; case 47: result += "/"; break; case 98: result += "\b"; break; case 102: result += "\f"; break; case 110: result += "\n"; break; case 114: result += "\r"; break; case 116: result += " "; break; case 117: const ch3 = scanHexDigits(4, true); if (ch3 >= 0) { result += String.fromCharCode(ch3); } else { scanError = 4; } break; default: scanError = 5; } start = pos; continue; } if (ch2 >= 0 && ch2 <= 31) { if (isLineBreak(ch2)) { result += text.substring(start, pos); scanError = 2; break; } else { scanError = 6; } } pos++; } return result; } __name(scanString, "scanString"); __name2(scanString, "scanString"); function scanNext() { value = ""; scanError = 0; tokenOffset = pos; lineStartOffset = lineNumber; prevTokenLineStartOffset = tokenLineStartOffset; if (pos >= len) { tokenOffset = len; return token = 17; } let code = text.charCodeAt(pos); if (isWhiteSpace(code)) { do { pos++; value += String.fromCharCode(code); code = text.charCodeAt(pos); } while (isWhiteSpace(code)); return token = 15; } if (isLineBreak(code)) { pos++; value += String.fromCharCode(code); if (code === 13 && text.charCodeAt(pos) === 10) { pos++; value += "\n"; } lineNumber++; tokenLineStartOffset = pos; return token = 14; } switch (code) { // tokens: []{}:, case 123: pos++; return token = 1; case 125: pos++; return token = 2; case 91: pos++; return token = 3; case 93: pos++; return token = 4; case 58: pos++; return token = 6; case 44: pos++; return token = 5; // strings case 34: pos++; value = scanString(); return token = 10; // comments case 47: const start = pos - 1; if (text.charCodeAt(pos + 1) === 47) { pos += 2; while (pos < len) { if (isLineBreak(text.charCodeAt(pos))) { break; } pos++; } value = text.substring(start, pos); return token = 12; } if (text.charCodeAt(pos + 1) === 42) { pos += 2; const safeLength = len - 1; let commentClosed = false; while (pos < safeLength) { const ch2 = text.charCodeAt(pos); if (ch2 === 42 && text.charCodeAt(pos + 1) === 47) { pos += 2; commentClosed = true; break; } pos++; if (isLineBreak(ch2)) { if (ch2 === 13 && text.charCodeAt(pos) === 10) { pos++; } lineNumber++; tokenLineStartOffset = pos; } } if (!commentClosed) { pos++; scanError = 1; } value = text.substring(start, pos); return token = 13; } value += String.fromCharCode(code); pos++; return token = 16; // numbers case 45: value += String.fromCharCode(code); pos++; if (pos === len || !isDigit(text.charCodeAt(pos))) { return token = 16; } // found a minus, followed by a number so // we fall through to proceed with scanning // numbers case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: value += scanNumber(); return token = 11; // literals and unknown symbols default: while (pos < len && isUnknownContentCharacter(code)) { pos++; code = text.charCodeAt(pos); } if (tokenOffset !== pos) { value = text.substring(tokenOffset, pos); switch (value) { case "true": return token = 8; case "false": return token = 9; case "null": return token = 7; } return token = 16; } value += String.fromCharCode(code); pos++; return token = 16; } } __name(scanNext, "scanNext"); __name2(scanNext, "scanNext"); function isUnknownContentCharacter(code) { if (isWhiteSpace(code) || isLineBreak(code)) { return false; } switch (code) { case 125: case 93: case 123: case 91: case 34: case 58: case 44: case 47: return false; } return true; } __name(isUnknownContentCharacter, "isUnknownContentCharacter"); __name2(isUnknownContentCharacter, "isUnknownContentCharacter"); function scanNextNonTrivia() { let result; do { result = scanNext(); } while (result >= 12 && result <= 15); return result; } __name(scanNextNonTrivia, "scanNextNonTrivia"); __name2(scanNextNonTrivia, "scanNextNonTrivia"); return { setPosition, getPosition: /* @__PURE__ */ __name2(() => pos, "getPosition"), scan: ignoreTrivia ? scanNextNonTrivia : scanNext, getToken: /* @__PURE__ */ __name2(() => token, "getToken"), getTokenValue: /* @__PURE__ */ __name2(() => value, "getTokenValue"), getTokenOffset: /* @__PURE__ */ __name2(() => tokenOffset, "getTokenOffset"), getTokenLength: /* @__PURE__ */ __name2(() => pos - tokenOffset, "getTokenLength"), getTokenStartLine: /* @__PURE__ */ __name2(() => lineStartOffset, "getTokenStartLine"), getTokenStartCharacter: /* @__PURE__ */ __name2(() => tokenOffset - prevTokenLineStartOffset, "getTokenStartCharacter"), getTokenError: /* @__PURE__ */ __name2(() => scanError, "getTokenError") }; } function isWhiteSpace(ch2) { return ch2 === 32 || ch2 === 9; } function isLineBreak(ch2) { return ch2 === 10 || ch2 === 13; } function isDigit(ch2) { return ch2 >= 48 && ch2 <= 57; } function format(documentText, range, options) { let initialIndentLevel; let formatText; let formatTextStart; let rangeStart; let rangeEnd; if (range) { rangeStart = range.offset; rangeEnd = rangeStart + range.length; formatTextStart = rangeStart; while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) { formatTextStart--; } let endOffset = rangeEnd; while (endOffset < documentText.length && !isEOL(documentText, endOffset)) { endOffset++; } formatText = documentText.substring(formatTextStart, endOffset); initialIndentLevel = computeIndentLevel(formatText, options); } else { formatText = documentText; initialIndentLevel = 0; formatTextStart = 0; rangeStart = 0; rangeEnd = documentText.length; } const eol = getEOL(options, documentText); let numberLineBreaks = 0; let indentLevel = 0; let indentValue; if (options.insertSpaces) { indentValue = repeat(" ", options.tabSize || 4); } else { indentValue = " "; } let scanner = createScanner(formatText, false); let hasError = false; function newLinesAndIndent() { if (numberLineBreaks > 1) { return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel); } else { return eol + repeat(indentValue, initialIndentLevel + indentLevel); } } __name(newLinesAndIndent, "newLinesAndIndent"); __name2(newLinesAndIndent, "newLinesAndIndent"); function scanNext() { let token = scanner.scan(); numberLineBreaks = 0; while (token === 15 || token === 14) { if (token === 14 && options.keepLines) { numberLineBreaks += 1; } else if (token === 14) { numberLineBreaks = 1; } token = scanner.scan(); } hasError = token === 16 || scanner.getTokenError() !== 0; return token; } __name(scanNext, "scanNext"); __name2(scanNext, "scanNext"); const editOperations = []; function addEdit(text, startOffset, endOffset) { if (!hasError && (!range || startOffset < rangeEnd && endOffset > rangeStart) && documentText.substring(startOffset, endOffset) !== text) { editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text }); } } __name(addEdit, "addEdit"); __name2(addEdit, "addEdit"); let firstToken = scanNext(); if (options.keepLines && numberLineBreaks > 0) { addEdit(repeat(eol, numberLineBreaks), 0, 0); } if (firstToken !== 17) { let firstTokenStart = scanner.getTokenOffset() + formatTextStart; let initialIndent = repeat(indentValue, initialIndentLevel); addEdit(initialIndent, formatTextStart, firstTokenStart); } while (firstToken !== 17) { let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart; let secondToken = scanNext(); let replaceContent = ""; let needsLineBreak = false; while (numberLineBreaks === 0 && (secondToken === 12 || secondToken === 13)) { let commentTokenStart = scanner.getTokenOffset() + formatTextStart; addEdit(" ", firstTokenEnd, commentTokenStart); firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart; needsLineBreak = secondToken === 12; replaceContent = needsLineBreak ? newLinesAndIndent() : ""; secondToken = scanNext(); } if (secondToken === 2) { if (firstToken !== 1) { indentLevel--; } if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1) { replaceContent = newLinesAndIndent(); } else if (options.keepLines) { replaceContent = " "; } } else if (secondToken === 4) { if (firstToken !== 3) { indentLevel--; } if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3) { replaceContent = newLinesAndIndent(); } else if (options.keepLines) { replaceContent = " "; } } else { switch (firstToken) { case 3: case 1: indentLevel++; if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) { replaceContent = newLinesAndIndent(); } else { replaceContent = " "; } break; case 5: if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) { replaceContent = newLinesAndIndent(); } else { replaceContent = " "; } break; case 12: replaceContent = newLinesAndIndent(); break; case 13: if (numberLineBreaks > 0) { replaceContent = newLinesAndIndent(); } else if (!needsLineBreak) { replaceContent = " "; } break; case 6: if (options.keepLines && numberLineBreaks > 0) { replaceContent = newLinesAndIndent(); } else if (!needsLineBreak) { replaceContent = " "; } break; case 10: if (options.keepLines && numberLineBreaks > 0) { replaceContent = newLinesAndIndent(); } else if (secondToken === 6 && !needsLineBreak) { replaceContent = ""; } break; case 7: case 8: case 9: case 11: case 2: case 4: if (options.keepLines && numberLineBreaks > 0) { replaceContent = newLinesAndIndent(); } else { if ((secondToken === 12 || secondToken === 13) && !needsLineBreak) { replaceContent = " "; } else if (secondToken !== 5 && secondToken !== 17) { hasError = true; } } break; case 16: hasError = true; break; } if (numberLineBreaks > 0 && (secondToken === 12 || secondToken === 13)) { replaceContent = newLinesAndIndent(); } } if (secondToken === 17) { if (options.keepLines && numberLineBreaks > 0) { replaceContent = newLinesAndIndent(); } else { replaceContent = options.insertFinalNewline ? eol : ""; } } const secondTokenStart = scanner.getTokenOffset() + formatTextStart; addEdit(replaceContent, firstTokenEnd, secondTokenStart); firstToken = secondToken; } return editOperations; } function repeat(s7, count) { let result = ""; for (let i7 = 0; i7 < count; i7++) { result += s7; } return result; } function computeIndentLevel(content, options) { let i7 = 0; let nChars = 0; const tabSize = options.tabSize || 4; while (i7 < content.length) { let ch2 = content.charAt(i7); if (ch2 === " ") { nChars++; } else if (ch2 === " ") { nChars += tabSize; } else { break; } i7++; } return Math.floor(nChars / tabSize); } function getEOL(options, text) { for (let i7 = 0; i7 < text.length; i7++) { const ch2 = text.charAt(i7); if (ch2 === "\r") { if (i7 + 1 < text.length && text.charAt(i7 + 1) === "\n") { return "\r\n"; } return "\r"; } else if (ch2 === "\n") { return "\n"; } } return options && options.eol || "\n"; } function isEOL(text, offset) { return "\r\n".indexOf(text.charAt(offset)) !== -1; } function parse(text, errors = [], options = ParseOptions.DEFAULT) { let currentProperty = null; let currentParent = []; const previousParents = []; function onValue(value) { if (Array.isArray(currentParent)) { currentParent.push(value); } else if (currentProperty !== null) { currentParent[currentProperty] = value; } } __name(onValue, "onValue"); __name2(onValue, "onValue"); const visitor = { onObjectBegin: /* @__PURE__ */ __name2(() => { const object = {}; onValue(object); previousParents.push(currentParent); currentParent = object; currentProperty = null; }, "onObjectBegin"), onObjectProperty: /* @__PURE__ */ __name2((name2) => { currentProperty = name2; }, "onObjectProperty"), onObjectEnd: /* @__PURE__ */ __name2(() => { currentParent = previousParents.pop(); }, "onObjectEnd"), onArrayBegin: /* @__PURE__ */ __name2(() => { const array = []; onValue(array); previousParents.push(currentParent); currentParent = array; currentProperty = null; }, "onArrayBegin"), onArrayEnd: /* @__PURE__ */ __name2(() => { currentParent = previousParents.pop(); }, "onArrayEnd"), onLiteralValue: onValue, onError: /* @__PURE__ */ __name2((error2, offset, length) => { errors.push({ error: error2, offset, length }); }, "onError") }; visit(text, visitor, options); return currentParent[0]; } function parseTree(text, errors = [], options = ParseOptions.DEFAULT) { let currentParent = { type: "array", offset: -1, length: -1, children: [], parent: void 0 }; function ensurePropertyComplete(endOffset) { if (currentParent.type === "property") { currentParent.length = endOffset - currentParent.offset; currentParent = currentParent.parent; } } __name(ensurePropertyComplete, "ensurePropertyComplete"); __name2(ensurePropertyComplete, "ensurePropertyComplete"); function onValue(valueNode) { currentParent.children.push(valueNode); return valueNode; } __name(onValue, "onValue"); __name2(onValue, "onValue"); const visitor = { onObjectBegin: /* @__PURE__ */ __name2((offset) => { currentParent = onValue({ type: "object", offset, length: -1, parent: currentParent, children: [] }); }, "onObjectBegin"), onObjectProperty: /* @__PURE__ */ __name2((name2, offset, length) => { currentParent = onValue({ type: "property", offset, length: -1, parent: currentParent, children: [] }); currentParent.children.push({ type: "string", value: name2, offset, length, parent: currentParent }); }, "onObjectProperty"), onObjectEnd: /* @__PURE__ */ __name2((offset, length) => { ensurePropertyComplete(offset + length); currentParent.length = offset + length - currentParent.offset; currentParent = currentParent.parent; ensurePropertyComplete(offset + length); }, "onObjectEnd"), onArrayBegin: /* @__PURE__ */ __name2((offset, length) => { currentParent = onValue({ type: "array", offset, length: -1, parent: currentParent, children: [] }); }, "onArrayBegin"), onArrayEnd: /* @__PURE__ */ __name2((offset, length) => { currentParent.length = offset + length - currentParent.offset; currentParent = currentParent.parent; ensurePropertyComplete(offset + length); }, "onArrayEnd"), onLiteralValue: /* @__PURE__ */ __name2((value, offset, length) => { onValue({ type: getNodeType(value), offset, length, parent: currentParent, value }); ensurePropertyComplete(offset + length); }, "onLiteralValue"), onSeparator: /* @__PURE__ */ __name2((sep6, offset, length) => { if (currentParent.type === "property") { if (sep6 === ":") { currentParent.colonOffset = offset; } else if (sep6 === ",") { ensurePropertyComplete(offset); } } }, "onSeparator"), onError: /* @__PURE__ */ __name2((error2, offset, length) => { errors.push({ error: error2, offset, length }); }, "onError") }; visit(text, visitor, options); const result = currentParent.children[0]; if (result) { delete result.parent; } return result; } function findNodeAtLocation(root, path210) { if (!root) { return void 0; } let node2 = root; for (let segment of path210) { if (typeof segment === "string") { if (node2.type !== "object" || !Array.isArray(node2.children)) { return void 0; } let found = false; for (const propertyNode of node2.children) { if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) { node2 = propertyNode.children[1]; found = true; break; } } if (!found) { return void 0; } } else { const index = segment; if (node2.type !== "array" || index < 0 || !Array.isArray(node2.children) || index >= node2.children.length) { return void 0; } node2 = node2.children[index]; } } return node2; } function visit(text, visitor, options = ParseOptions.DEFAULT) { const _scanner = createScanner(text, false); const _jsonPath = []; function toNoArgVisit(visitFunction) { return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true; } __name(toNoArgVisit, "toNoArgVisit"); __name2(toNoArgVisit, "toNoArgVisit"); function toNoArgVisitWithPath(visitFunction) { return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true; } __name(toNoArgVisitWithPath, "toNoArgVisitWithPath"); __name2(toNoArgVisitWithPath, "toNoArgVisitWithPath"); function toOneArgVisit(visitFunction) { return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true; } __name(toOneArgVisit, "toOneArgVisit"); __name2(toOneArgVisit, "toOneArgVisit"); function toOneArgVisitWithPath(visitFunction) { return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true; } __name(toOneArgVisitWithPath, "toOneArgVisitWithPath"); __name2(toOneArgVisitWithPath, "toOneArgVisitWithPath"); const onObjectBegin = toNoArgVisitWithPath(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisitWithPath(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError); const disallowComments = options && options.disallowComments; const allowTrailingComma = options && options.allowTrailingComma; function scanNext() { while (true) { const token = _scanner.scan(); switch (_scanner.getTokenError()) { case 4: handleError2( 14 /* ParseErrorCode.InvalidUnicode */ ); break; case 5: handleError2( 15 /* ParseErrorCode.InvalidEscapeCharacter */ ); break; case 3: handleError2( 13 /* ParseErrorCode.UnexpectedEndOfNumber */ ); break; case 1: if (!disallowComments) { handleError2( 11 /* ParseErrorCode.UnexpectedEndOfComment */ ); } break; case 2: handleError2( 12 /* ParseErrorCode.UnexpectedEndOfString */ ); break; case 6: handleError2( 16 /* ParseErrorCode.InvalidCharacter */ ); break; } switch (token) { case 12: case 13: if (disallowComments) { handleError2( 10 /* ParseErrorCode.InvalidCommentToken */ ); } else { onComment(); } break; case 16: handleError2( 1 /* ParseErrorCode.InvalidSymbol */ ); break;