format.ts 843 B

12345678910111213141516171819202122232425262728
  1. export function prettyObject(msg: any) {
  2. const obj = msg;
  3. if (typeof msg !== "string") {
  4. msg = JSON.stringify(msg, null, " ");
  5. }
  6. if (msg === "{}") {
  7. return obj.toString();
  8. }
  9. if (msg.startsWith("```json")) {
  10. return msg;
  11. }
  12. return ["```json", msg, "```"].join("\n");
  13. }
  14. export function* chunks(s: string, maxBytes = 1000 * 1000) {
  15. const decoder = new TextDecoder("utf-8");
  16. let buf = new TextEncoder().encode(s);
  17. while (buf.length) {
  18. let i = buf.lastIndexOf(32, maxBytes + 1);
  19. // If no space found, try forward search
  20. if (i < 0) i = buf.indexOf(32, maxBytes);
  21. // If there's no space at all, take all
  22. if (i < 0) i = buf.length;
  23. // This is a safe cut-off point; never half-way a multi-byte
  24. yield decoder.decode(buf.slice(0, i));
  25. buf = buf.slice(i + 1); // Skip space (if any)
  26. }
  27. }