{
  "version": 1,
  "workflows": [
    {
      "id": "4280BC6B-D759-4A35-919E-D5B6EA436AFB",
      "workflowVersion": 1,
      "name": "Text Cleanup",
      "summary": "Trim · Empty Lines · Join · Spaces · Line Endings",
      "symbolName": "wand.and.stars",
      "isEnabled": true,
      "requiresTrustConfirmation": false,
      "sortOrder": 0,
      "mode": "scriptFilter",
      "supportedTypes": [
        "text",
        "markdown"
      ],
      "script": {
        "source": "inline",
        "code": "ObjC.import(\"Foundation\");\n\nfunction readJSON() {\n    var data = $.NSFileHandle.fileHandleWithStandardInput.readDataToEndOfFile;\n    var text = $.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding);\n    if (!text) throw new Error(\"Workflow input is not valid UTF-8\");\n    return JSON.parse(text.js);\n}\n\nfunction writeJSON(value) {\n    var text = JSON.stringify(value);\n    var data = $(text).dataUsingEncoding($.NSUTF8StringEncoding);\n    $.NSFileHandle.fileHandleWithStandardOutput.writeData(data);\n}\n\nfunction textResult(value) {\n    writeJSON({\n        version: 1,\n        result: {\n            type: \"text\",\n            value: String(value)\n        }\n    });\n}\n\nfunction filesResult(paths) {\n    writeJSON({\n        version: 1,\n        result: {\n            type: \"files\",\n            paths: paths\n        }\n    });\n}\n\nfunction preview(value) {\n    var compact = String(value).replace(/\\s+/g, \" \").trim();\n    return compact.length > 90 ? compact.slice(0, 87) + \"...\" : compact;\n}\n\nfunction normalizedLineEndings(value) {\n    return String(value).replace(/\\r\\n?/g, \"\\n\");\n}\n\nfunction fileRepresentations(payload) {\n    var items = (payload.paste && payload.paste.representations) || [];\n    return items.filter(function (item) {\n        return item.path && String(item.path).length > 0;\n    });\n}\n\nfunction inputFileRepresentations(payload, allowedTypes) {\n    var pasteType = payload.paste && payload.paste.type;\n    if (allowedTypes.indexOf(pasteType) < 0) return [];\n    return fileRepresentations(payload);\n}\n\nfunction firstInputFile(payload, allowedTypes) {\n    var files = inputFileRepresentations(payload, allowedTypes);\n    return files.length ? files[0] : null;\n}\n\nfunction readFileData(filePath) {\n    var data = $.NSData.dataWithContentsOfFile($(filePath));\n    if (!data) throw new Error(\"Unable to read input file\");\n    return data;\n}\n\nfunction utf8String(data) {\n    var text = $.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding);\n    return text ? text.js : null;\n}\n\nfunction readFileText(filePath) {\n    var text = utf8String(readFileData(filePath));\n    if (text === null) throw new Error(\"Input file is not valid UTF-8 text\");\n    return text;\n}\n\nfunction safeFileName(value) {\n    var name = String(value || \"output\").split(\"/\").pop();\n    name = name.replace(/[:\\u0000-\\u001f]/g, \"-\");\n    return name || \"output\";\n}\n\nfunction uniqueFileName(prefix, extensionName) {\n    var timestamp = Math.floor(Date.now() / 1000);\n    var suffix = $.NSUUID.UUID.UUIDString.js.slice(0, 8).toLowerCase();\n    return prefix + \"-\" + timestamp + \"-\" + suffix + \".\" + extensionName;\n}\n\nfunction outputPath(payload, fileName) {\n    return payload.directories.output + \"/\" + safeFileName(fileName);\n}\n\nfunction runTask(executable, arguments) {\n    var task = $.NSTask.alloc.init;\n    var outputPipe = $.NSPipe.pipe;\n    var errorPipe = $.NSPipe.pipe;\n    task.launchPath = executable;\n    task.arguments = $(arguments);\n    task.standardOutput = outputPipe;\n    task.standardError = errorPipe;\n    task.launch;\n    task.waitUntilExit;\n\n    var stdoutData = outputPipe.fileHandleForReading.readDataToEndOfFile;\n    var stderrData = errorPipe.fileHandleForReading.readDataToEndOfFile;\n    var stdoutText = $.NSString.alloc.initWithDataEncoding(\n        stdoutData,\n        $.NSUTF8StringEncoding\n    );\n    var stderrText = $.NSString.alloc.initWithDataEncoding(\n        stderrData,\n        $.NSUTF8StringEncoding\n    );\n    return {\n        status: Number(task.terminationStatus),\n        stdout: stdoutText ? stdoutText.js : \"\",\n        stderr: stderrText ? stderrText.js : \"\"\n    };\n}\n\nfunction transformations(input) {\n    var normalized = normalizedLineEndings(input);\n    return [\n        {\n            id: \"trimWhitespace\",\n            title: \"Trim Whitespace\",\n            icon: \"text.alignleft\",\n            value: String(input).trim()\n        },\n        {\n            id: \"removeEmptyLines\",\n            title: \"Remove Empty Lines\",\n            icon: \"line.3.horizontal.decrease\",\n            value: normalized.split(\"\\n\").filter(function (line) {\n                return line.trim().length > 0;\n            }).join(\"\\n\")\n        },\n        {\n            id: \"joinLines\",\n            title: \"Join Lines\",\n            icon: \"arrow.right.to.line\",\n            value: normalized.split(\"\\n\").map(function (line) {\n                return line.trim();\n            }).filter(function (line) {\n                return line.length > 0;\n            }).join(\" \")\n        },\n        {\n            id: \"collapseSpaces\",\n            title: \"Collapse Spaces\",\n            icon: \"space\",\n            value: normalized.replace(/[ \\t\\f\\v]+/g, \" \")\n        },\n        {\n            id: \"normalizeLineEndings\",\n            title: \"Normalize Line Endings\",\n            icon: \"return\",\n            value: normalized\n        }\n    ];\n}\n\nfunction main() {\n    var payload = readJSON();\n    var input = (payload.paste && payload.paste.text) || \"\";\n    var items = transformations(input);\n\n    if (payload.phase === \"filter\") {\n        writeJSON({\n            version: 1,\n            actions: items.filter(function (item) {\n                return item.value !== input;\n            }).map(function (item) {\n                return {\n                    id: item.id,\n                    title: item.title,\n                    subtitle: preview(item.value),\n                    icon: item.icon,\n                    argument: { operation: item.id }\n                };\n            })\n        });\n        return;\n    }\n\n    if (payload.phase === \"execute\") {\n        var operation = (payload.argument && payload.argument.operation) || payload.actionID;\n        var selected = items.filter(function (item) { return item.id === operation; })[0];\n        if (!selected) throw new Error(\"Unknown text cleanup operation\");\n        textResult(selected.value);\n        return;\n    }\n    throw new Error(\"Unsupported workflow phase\");\n}\n\nmain();\n",
        "scriptPath": "",
        "interpreterPath": "/usr/bin/osascript",
        "arguments": [
          "-l",
          "JavaScript"
        ],
        "workingDirectory": "",
        "filterTimeout": 5,
        "executeTimeout": 15
      }
    }
  ]
}
