Skip to content

MaksymStoianov/apps-script-utils

Project banner for Google Apps Script Utils

Artist: Daryna Mikhailenko

Utilities for Google Apps Script™

Built with clasp License Security Policy Roadmap Latest release

GitHub Stars GitHub Fork GitHub Sponsors

Overview

A set of utilities for Google Apps Script, as well as common functions for working with data, strings, validation and more. This project aims to simplify development in the Apps Script environment and provide frequently used functions in one place.

Key Features

  • 🚀 Optimized for GAS: Tailored specifically for Google Apps Script environments and limitations.
  • 🛠️ Rich Utility Set: Comprehensive collection of spreadsheet, UI, and admin SDK helpers.
  • 📝 TypeScript Support: Full type definitions for better IDE support and safer code.
  • 🧪 Tested: Unit tests using Vitest to ensure reliability.
  • 🔗 Linked Documentation: Direct links to official Google documentation for all GAS types.
  • 🛡️ Robust Error Handling: Custom exception classes for better debugging.

Requirements

Installation

Install the package via npm:

npm install apps-script-utils

Usage Examples

📊 Working with Sheets

Append multiple rows of data efficiently:

import { appendRows } from "apps-script-utils";

const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
const data = [
  ["John Doe", "john@example.com", 28],
  ["Jane Smith", "jane@example.com", 32]
];

appendRows(sheet, data);

🔐 Admin SDK Utilities

Check if the current user has administrative privileges:

import { isAdmin } from "apps-script-utils";

if (isAdmin()) {
  Logger.log("Access granted to admin panel.");
} else {
  Logger.log("Access denied.");
}

📍 A1 Notation Parsing

Parse complex A1 notations into structured objects:

import { parseA1Notation } from "apps-script-utils";

const rangeInfo = parseA1Notation("'Sheet1'!A1:B10");

console.log(rangeInfo.sheetName); // "Sheet1"
console.log(rangeInfo.startRowIndex); // 0
console.log(rangeInfo.endColumnIndex); // 2

Development

Scripts

The following scripts are available in package.json:

  • npm run build: Cleans the dist directory and compiles the TypeScript source.
  • npm run dev: Starts Vitest in watch mode.
  • npm test: Runs all tests once.
  • npm run lint: Runs ESLint with auto-fix enabled.
  • npm run format: Formats the codebase using Prettier.
  • npm run maint: Runs the maintenance script (scripts/maintenance.sh).
  • npm run prepare: Sets up Husky for git hooks.

Testing

The project uses Vitest for testing. You can run tests using:

npm test

For development with watch mode:

npm run dev

Project Structure

.
├── config/           # Configuration files
├── dist/             # Compiled output (after build)
├── docs/             # Documentation and assets
├── scripts/          # Maintenance and helper scripts
├── src/              # Source code
│   ├── appsscript/   # Google Apps Script specific utilities
│   ├── exception/    # Custom exception classes
│   ├── html/         # HTML utilities
│   ├── json/         # JSON utilities
│   ├── lang/         # Language-level utilities (array, string, etc.)
│   ├── net/          # Network and path utilities
│   ├── time/         # Time-related utilities
│   └── index.ts      # Main entry point
├── test/             # Unit tests
└── vitest.config.ts  # Vitest configuration

Functions by Category

1. Google Apps Script Module

Functions specifically designed for Google Apps Script environments, including utilities for working with spreadsheets.

Functions

1.1. Google Base Methods

Functions that enable various operations on a collection of base utility methods.

Functions
Function Return type Brief description
getByteSize Number Calculates the size of a string in bytes (UTF-8).

1.2. Google Admin SDK Directory Methods

Functions that enable various operations on the Admin SDK Directory Service.

Functions
Function Return type Brief description
isAdmin Boolean Checks if the current user is an administrator of the Google Workspace domain.

1.3. Google Drive Methods

Functions that enable various operations on Google Drive.

Functions
Function Return type Brief description

1.4. Google Docs Methods

Functions that enable various operations on Google Docs.

Functions
Function Return type Brief description

1.5. Google Forms Methods

Functions that enable various operations on Google Forms.

Functions
Function Return type Brief description

1.6. Google Sheets Methods

Functions that enable various operations on Google Sheets.

Functions
Function Return type Brief description
appendColumn Sheet Appends a single column of data to the right of the current data area.
appendColumns Sheet Appends multiple columns of data to the right of the current data area.
appendRow Sheet Appends a single row of data to the bottom of the current data area.
appendRows Sheet Appends multiple rows of data to the bottom of the current data area.
convertRichTextToHtml String Converts a RichTextValue to its HTML representation.
doGridRangesIntersect Boolean Checks if two GridRange objects overlap on the same sheet.
extractRangeFromA1Notation 🆕 String | null Extracts the range part (e.g., A1:B2) from a full A1 notation string.
extractSheetNameFromA1Notation String | null Extracts the sheet name part from an A1 notation string.
getColumnIndexByLetter Number | null Converts a column letter (e.g., A) to a 0-based column index.
getColumnLetterByIndex String Converts a 0-based column index to its letter representation (e.g., 0 -> A).
getColumnLetterByPosition String Converts a 1-based column position to its letter representation.
getColumnPositionByLetter Number | null Converts a column letter to a 1-based column position.
getSheetById Sheet | null Retrieves a Sheet object by its unique ID.
getSheetByIndex Sheet | null Retrieves a Sheet object by its zero-based index.
highlightHtml String Applies syntax highlighting to an HTML string.
isCellGridRange Boolean Validates if a GridRange represents exactly one cell.
isGridRangeContainedIn Boolean Determines if one GridRange is fully enclosed within another.
isGridRangeSameDimensions Boolean Checks if two GridRange objects have identical height and width.
isRange Boolean Validates if a value is a Google Apps Script Range object.
isRichTextValue Boolean Validates if a value is a Google Apps Script RichTextValue object.
isSheet Boolean Validates if a value is a Google Apps Script Sheet object.
isSpreadsheet Boolean Validates if a value is a Google Apps Script Spreadsheet object.
isTextStyle Boolean Validates if a value is a Google Apps Script TextStyle object.
isValidSheetId Boolean Validates the format of a sheet ID.
isValidSheetName Boolean Validates if a string is a valid Google Sheets name.
isValidSpreadsheetId Boolean Validates the format of a Google Spreadsheet ID.
nonRange Boolean Checks if a value is NOT a Google Apps Script Range.
nonSheet Boolean Checks if a value is NOT a Google Apps Script Sheet.
parseA1Notation 🆕 GridRange Parses an A1 notation string into a structured GridRange object.
parseA1Notations 🆕 GridRange[] Parses a list of comma-separated A1 notations into an array of GridRange objects.
prependRow Sheet Inserts a single row of data at the top of the data area.
prependRows Sheet Inserts multiple rows of data at the top of the data area.
requireRange Range Ensures a value is a Range, otherwise throws an exception.
requireSheet Sheet Ensures a value is a Sheet, otherwise throws an exception.
requireSpreadsheet 🆕 Spreadsheet Ensures a value is a Spreadsheet, otherwise throws an exception.
sortSheets void Alphabetically sorts all sheets within a spreadsheet.
toA1Notation String Converts a GridRange object back to A1 notation.
updateSheetNameInA1Notation 🆕 String Updates or sets the sheet name within an A1 notation string while preserving the range.

1.7. Google Slides Methods

Functions that enable various operations on Google Slides.

Functions
Function Return type Brief description
convertMarkdownToRichText 🆕 RichTextRun[] Converts Markdown-formatted text to an array of RichTextRun objects.
findReplaceAllTextInSlide 🆕 Number Finds and replaces all occurrences of text within a slide.
getSlideByIndex 🆕 Slide | null Retrieves a Slide object by its zero-based index.
getSlideIndex 🆕 Number | null Retrieves the zero-based index of a Slide within its presentation.
isPresentation 🆕 Boolean Validates if a value is a Google Apps Script Presentation object.
isSlide 🆕 Boolean Validates if a value is a Google Apps Script Slide object.
isValidPresentationId 🆕 Boolean Validates if a string is a valid Google Slides presentation ID.
isValidSlideId 🆕 Boolean Validates if a string is a valid Google Slides slide ID.
requireSlide 🆕 Slide Ensures a value is a Slide, otherwise throws an exception.

1.8. Network Methods

Functions that enable various network-related operations.

Functions
Function Return type Brief description
requireValidToken 🆕 String Ensures that a valid token is provided and matches the allowed keys.

1.9. Google UI Methods

Functions that enable various operations on the user interface, including sidebars, dialogs, and web apps.

Functions
Function Return type Brief description
checkMultipleAccount Boolean Detects if the user is logged into multiple Google accounts simultaneously.
isHtmlOutput Boolean Validates if a value is a Google Apps Script HtmlOutput object.
isTextOutput Boolean Validates if a value is a Google Apps Script TextOutput object.
isUi Boolean Validates if a value is a Google Apps Script Ui object.
requireRepository 🆕 T Ensures that a repository is defined.
requireService 🆕 T Ensures that a service is defined.

2. Base Utilities

This package contains core utility functions that are not tied to a specific Apps Script service.

Functions
Function Return type Brief description
chunk Array Divides an array into multiple smaller arrays of a specified size.
decodeHtml String Decodes HTML entities (e.g., & -> &) back to plain text.
encodeHtml String Encodes a string for safe rendering in HTML.
escapeHtml String Escapes special characters (<, >, &, etc.) for HTML.
escapeRegExp String Escapes special characters for safe use within regular expressions.
escapeXml String Escapes special characters for safe use in XML documents.
hashCode Number Generates a numeric hash code for a given string.
is2DArray Boolean Validates if a value is a two-dimensional array.
isArray Boolean Validates if a value is an Array.
isBoolean Boolean Validates if a value is a boolean.
isConsistent2DArray Boolean Validates if a 2D array has uniform inner array lengths.
isCountable Boolean Checks if a value is a non-negative safe integer.
isEmail Boolean Validates if a string follows a proper email format.
isEmpty Boolean Checks if a value is considered empty (null, undefined, empty string/array/object).
isException Boolean Validates if a value is an instance of Exception or a derived class.
isFunction Boolean Validates if a value is a function.
isFunctionLike Boolean Validates if a value is "function-like" (e.g., callable).
isInteger Boolean Checks if a value is a number and an integer.
isLength Boolean Validates if a value is a valid array-like length.
isNil Boolean Checks if a value is null or undefined.
isNull Boolean Checks if a value is null.
isNumber Boolean Validates if a value is a number.
isNumberLike Boolean Checks if a value can be reliably converted to a number.
isObject Boolean Validates if a value is a plain object (excluding null and arrays).
isObjectLike Boolean Checks if a value is an object (including arrays and functions).
isRegExp Boolean Validates if a value is a regular expression.
isScalar Boolean Checks if a value is a primitive scalar type (string, number, boolean, symbol, bigint).
isString Boolean Validates if a value is a string.
isSymbol Boolean Validates if a value is a symbol.
nonEmptyString 🆕 String Validates that the given value is a non-empty string.
isUndefined Boolean Checks if a value is undefined.
isUrl Boolean Validates if a string is a properly formatted URL.
isValidLocale Boolean Validates if a string is a valid BCP 47 locale code.
isValidSlug Boolean Validates if a string is a URL-friendly slug.
isValidVersion Boolean Validates if a string follows Semantic Versioning rules.
isVersionCompatible Boolean Determines if two version strings are compatible based on SemVer.
nonArray Boolean Checks if a value is NOT an Array.
nonBoolean Boolean Checks if a value is NOT a boolean.
nonEmpty Boolean Checks if a value is NOT empty.
nonFunction 🆕 Boolean Checks if a value is NOT a Function.
nonNil Boolean Checks if a value is NOT null or undefined.
nonNull Boolean Checks if a value is NOT null.
nonNegative Boolean Checks if a value is a non-negative number.
nonNumber Boolean Checks if a value is NOT a number.
nonScalar Boolean Checks if a value is NOT a scalar type.
nonString Boolean Checks if a value is NOT a string.
nonSymbol Boolean Checks if a value is NOT a Symbol.
nonUndefined Boolean Checks if a value is NOT undefined.
now Number Returns the current timestamp in milliseconds.
ObjectTag Enum Enum representing Object#toString result references in uppercase.
parseJson ⚠️ Object Safely parses a JSON string, handling potential errors.
requireNonEmptyString String Ensures a string is not empty, otherwise throws an exception.
requireNonNull any Ensures a value is not null, otherwise throws an exception.
requireString String Ensures a value is a string, otherwise throws an exception.
requireValidEmail String Ensures a string is a valid email, otherwise throws an exception.
stringifyJson String Safely converts an object to a JSON string.
toCamelCase String Converts a string to camelCase.
toInteger Number | null Converts a value to an integer, returning null on failure.
toKebabCase String Converts a string to kebab-case.
toLowerCase String Converts a string to lowercase.
toProperCase String Converts a string to Proper Case (capitalizing the first letter of each word).
toSnakeCase String Converts a string to snake_case.
toString String Converts any value to its string representation.
toUpperCase String Converts a string to uppercase.
transpose Array Flips a 2D array over its diagonal (swaps rows and columns).
versionCompare Number Compares two version strings, returning -1, 0, or 1.

3. Exceptions Module

This package is for all exception classes.

Functions
Exception Description
AdminDirectoryException Represents an exception thrown when the Admin SDK Directory Service is not available or enabled.
InvalidGridRangeException Represents an exception thrown when an invalid GridRange object is provided.
InvalidRangeException Represents an exception thrown when an invalid Range object is provided.
InvalidSheetException Represents an exception thrown when an invalid Sheet object is provided.
InvalidSpreadsheetException 🆕 Represents an exception thrown when an invalid Spreadsheet object is provided.
InvalidPresentationException 🆕 Represents an exception thrown when an invalid Presentation object is provided.
SlideNotFoundException 🆕 Represents an exception thrown when a Slide object is not found.
Exception Description
Exception Base class for all custom exceptions.
RuntimeException Exception thrown during application execution.
AuthenticationException 🆕 Exception thrown during authentication failures.
EmptyStringException Exception thrown when a non-empty string is required but an empty one is provided.
IllegalArgumentException Exception thrown when an invalid or inappropriate argument is passed to a method.
InvalidEmailFormatException Exception thrown when an email address does not follow the expected format.
InvalidStringException Exception thrown when a string is expected but another type is received.
NullPointerException Exception thrown when null is encountered where an object is required.
RepositoryIsNotDefinedException 🆕 Exception thrown when a repository is not defined.
ServiceIsNotDefinedException 🆕 Exception thrown when a service is not defined.

4. path Module

Functions for working with file paths and URLs.

Functions
Function Return type Brief description
isAbsolute Boolean Determines if a given path is an absolute path.
isRelative Boolean Determines if a given path is a relative path.
isValidDomain Boolean Validates if a string is a properly formatted domain name.
join String Joins all given path segments together using the platform-specific separator.
normalize String Normalizes a path by resolving . and .. segments.
parse ParsedPath Breaks down a path into an object containing its constituent parts (root, dir, base, ext, name).

5. abstracts and interfaces

Abstracts
Abstract Brief description
Class Base abstract class for providing common class functionality.
Interfaces
Interface Brief description
Iterator Interface for iterators.

Contributing

Contributions are welcome! If you'd like to contribute, please:

  1. Fork the repository.
  2. Create a new branch for your feature or bugfix.
  3. Write tests for your changes.
  4. Run npm run lint and npm run format.
  5. Do not modify CHANGELOG.md manually; it's updated automatically.
  6. Submit a pull request.

Please make sure to follow the existing code style and naming conventions.

Support

If you encounter any issues or have questions, please:

  • Open an issue on GitHub.
  • Check the Changelog for recent updates.
  • Support the project by giving it a ⭐ on GitHub!

Roadmap

For the project development plan and future features, please see the ROADMAP file.

Changelog

For a detailed list of changes and updates, please refer to the CHANGELOG file.

License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.


Like this project? Star our awesome repo »