Skip to content

Commit

Permalink
Truncate comments exceeding 8000 characters (fixes #36)
Browse files Browse the repository at this point in the history
  • Loading branch information
GarboMuffin committed Nov 26, 2024
1 parent 9895851 commit d6352fd
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/sb3fix.js
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,29 @@ const fixJSON = (data, options = {}) => {
}
};

/**
* @param {string} id
* @param {unknown} comment
*/
const fixCommentInPlace = (id, comment) => {
if (!isObject(comment)) {
throw new Error('comment is not an object');
}

if (typeof comment.text !== 'string') {
throw new Error('comment text is not a string');
}

// Scratch requires comments to not exceed 8000 characters.
// We'll store the excess in .extraText so the text won't be truncated if opened in TurboWarp.
const MAX_LENGTH = 8000;
if (comment.text.length > MAX_LENGTH) {
log(`comment ${id} had length ${comment.text.length}`);
comment.extraText = comment.text.substring(MAX_LENGTH);
comment.text = comment.text.substring(0, MAX_LENGTH);
}
};

/**
* @param {unknown} target
*/
Expand Down Expand Up @@ -287,6 +310,14 @@ const fixJSON = (data, options = {}) => {
fixBlockInPlace(blockId, block);
}

// Comments are not required
const comments = target.comments;
if (comments) {
for (const [commentId, comment] of Object.entries(comments)) {
fixCommentInPlace(commentId, comment);
}
}

const variables = target.variables;
if (!isObject(variables)) {
throw new Error('variables is not an object');
Expand Down
Binary file added tests/expected-output/very-long-comments.sb3
Binary file not shown.
3 changes: 3 additions & 0 deletions tests/expected-output/very-long-comments.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
checking target 0
comment d had length 8001
comment e had length 1000000
Binary file added tests/samples/very-long-comments.sb3
Binary file not shown.

0 comments on commit d6352fd

Please sign in to comment.