Remove IIFE wrapper from googleDriveAdapterHelper.js

Changed from IIFE pattern to direct object literal evaluation

Rationale:
- Global variable functions should evaluate to an object directly
- IIFE wrapper was unnecessary complexity
- Simpler pattern: code evaluates to object, not function that returns object
- Matches intended architecture for vm.Script module loading

Changes:
1. Removed IIFE wrapper:
   - Before: (function createHelpers() { ... return {...} })()
   - After: ({ ... })

2. Removed function indentation (2 spaces throughout file)

3. Updated constitution.md:
   - Pattern description: 'IIFE returning object' → 'evaluates to a single object'
   - Clarified: 'not wrapped in IIFE'
   - Updated all pattern references

Structure:
- File defines classes and functions at top level
- Final expression is object literal referencing all functions
- When executed via vm.Script, evaluates to the object
- Object is assigned to globalVariableContext.googleDriveAdapterHelper

Benefits:
 Simpler pattern (no function wrapper)
 Clearer intent (direct object evaluation)
 Matches architecture description
 Easier to understand and maintain
 Same functionality, cleaner implementation

Before (IIFE):

After (Object Literal):

Testing:
✓ Syntax validated
✓ Server starts successfully
✓ Module loads: 'Loaded global functions: googleDriveAdapterHelper'
✓ All function calls work correctly
✓ Request handling works as expected

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
2026-03-07 12:06:13 -06:00
parent 470f760b9b
commit c094d4d472
2 changed files with 254 additions and 258 deletions

View File

@@ -204,9 +204,9 @@ Follow-up TODOs:
**Helper Functions Pattern**: Pure utility functions (XML escaping, validation, formatting, routing) MAY be extracted to `src/globalVariables/googleDriveAdapterHelper.js` to improve readability and maintainability. The helpers module:
- MUST be loaded via `vm.Script` (same isolation as proxy.js)
- MUST return a single object with all helper functions
- MUST evaluate to a single JavaScript object with all helper functions
- MUST have ZERO imports/exports
- Is injected as `helpers` global object into VM context
- Is injected as `googleDriveAdapterHelper` global object into VM context
- Contains ONLY pure utilities, NO business logic or state
### I. Zero External Imports or Exports from `src/proxyScripts/proxy.js` (NON-NEGOTIABLE)
@@ -291,11 +291,11 @@ config/
**googleDriveAdapterHelper.js Pattern**:
- MUST be loaded using `vm.Script` (same isolation as proxy.js)
- MUST return single object with all helper functions via IIFE
- MUST evaluate to a single JavaScript object (not wrapped in IIFE)
- MUST have ZERO imports/exports (pure vm.Script execution)
- Loaded by `loadGlobalVariables()` which scans for both JSON and JS files
- Filename determines global key: `googleDriveAdapterHelper.js``globalVariableContext.helpers`
- Injected as `helpers` global object into VM context
- Filename determines global key: `googleDriveAdapterHelper.js``globalVariableContext.googleDriveAdapterHelper`
- Injected as `googleDriveAdapterHelper` global object into VM context
- Contains ONLY pure utilities: validators, formatters, XML, error mappers
- MUST NOT contain: authentication, API calls, state, business decisions
- Executed in context with full access to globalVMContext and globalVariableContext
@@ -441,7 +441,6 @@ script.runInContext(context);
10. **googleDriveAdapterHelper** - Pure utility functions object (OPTIONAL)
- Purpose: Extracted helper functions for code organization
- Source: `src/globalVariables/googleDriveAdapterHelper.js` loaded via `vm.Script`
- Pattern: IIFE returning object with all helper functions
- Loading: server.js loads via `loadGlobalVariables()` at startup
- Generic Loading Pattern:
- All .js files in globalVariables/ are loaded automatically

View File

@@ -17,43 +17,41 @@
* @returns {Object} Helpers object with all utility functions
*/
// Wrap in IIFE that returns helpers object
(function createHelpers() {
/**
/**
* Custom error for document count exceeding limit
*/
class DocumentCountExceededError extends Error {
constructor(count, limit) {
class DocumentCountExceededError extends Error {
constructor(count, limit) {
super(`Document count ${count} exceeds limit of ${limit}`);
this.name = "DocumentCountExceededError";
this.count = count;
this.limit = limit;
this.statusCode = 413;
}
}
}
}
// =============================================================================
// Utility Functions
// =============================================================================
// =============================================================================
// Utility Functions
// =============================================================================
/**
/**
* Generate a unique request ID for tracing
* Uses UUID v4 for uniqueness
*
* @returns {string} Request ID in format: req_<uuid>
*/
function generateRequestId() {
return `req_${crypto.randomUUID()}`;
}
function generateRequestId() {
return `req_${crypto.randomUUID()}`;
}
/**
/**
* Validate document ID format
* Google Drive IDs are alphanumeric with hyphens and underscores
*
* @param {string} id - Document ID to validate
* @returns {boolean} True if valid
*/
function validateDocumentId(id) {
function validateDocumentId(id) {
if (!id || typeof id !== "string") {
return false;
}
@@ -62,33 +60,33 @@
// Characters: a-z, A-Z, 0-9, -, _
const pattern = /^[a-zA-Z0-9_-]{8,128}$/;
return pattern.test(id);
}
}
/**
/**
* Validate document count against limit
*
* @param {number} count - Document count
* @param {number} limit - Maximum allowed (default: 50000)
* @throws {DocumentCountExceededError} If count > limit
*/
function validateDocumentCount(count, limit = 50000) {
function validateDocumentCount(count, limit = 50000) {
if (count > limit) {
throw new DocumentCountExceededError(count, limit);
}
}
}
// =============================================================================
// XML Utilities
// =============================================================================
// =============================================================================
// XML Utilities
// =============================================================================
/**
/**
* Escape special XML characters
* Prevents XML injection and ensures valid XML output
*
* @param {string} str - String to escape
* @returns {string} Escaped string safe for XML
*/
function escapeXml(str) {
function escapeXml(str) {
if (!str) return "";
return str
@@ -97,13 +95,13 @@
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&apos;");
}
}
// =============================================================================
// Error Mapping
// =============================================================================
// =============================================================================
// Error Mapping
// =============================================================================
/**
/**
* Map Drive API error to HTTP status code and retry info
*
* Per specification:
@@ -115,7 +113,7 @@
* @param {Error} error - Drive API error
* @returns {Object} { statusCode, retryAfter? }
*/
function mapDriveErrorToHttp(error) {
function mapDriveErrorToHttp(error) {
// Handle DocumentCountExceededError
if (error instanceof DocumentCountExceededError) {
return { statusCode: 413 };
@@ -148,13 +146,13 @@
// All other errors map to 500
return { statusCode: 500 };
}
}
// =============================================================================
// Sitemap Functions
// =============================================================================
// =============================================================================
// Sitemap Functions
// =============================================================================
/**
/**
* Transform Drive document to sitemap entry
*
* Creates RESTful URL in format: {baseUrl}/documents/{documentId}
@@ -166,7 +164,7 @@
* @param {string} baseUrl - Base URL for the adapter
* @returns {Object} Sitemap entry { loc, lastmod }
*/
function toSitemapEntry(document, baseUrl) {
function toSitemapEntry(document, baseUrl) {
if (!document || !document.id) {
console.error("Invalid document for sitemap entry", { document });
return null;
@@ -193,16 +191,16 @@
}
return { loc, lastmod };
}
}
/**
/**
* Transform array of Drive documents to sitemap entries
*
* @param {Array<Object>} documents - Array of Drive API documents
* @param {string} baseUrl - Base URL for the adapter
* @returns {Array<Object>} Array of sitemap entries
*/
function transformDocumentsToSitemapEntries(documents, baseUrl) {
function transformDocumentsToSitemapEntries(documents, baseUrl) {
if (!Array.isArray(documents)) {
console.error("Documents must be an array", { documents });
return [];
@@ -211,9 +209,9 @@
return documents
.map((doc) => toSitemapEntry(doc, baseUrl))
.filter((entry) => entry !== null);
}
}
/**
/**
* Generate XML sitemap from sitemap entries
*
* Handles empty sitemap (0 documents) case - returns valid XML with empty urlset.
@@ -221,7 +219,7 @@
* @param {Array<Object>} sitemapEntries - Array of { loc, lastmod } objects
* @returns {string} Complete XML sitemap string
*/
function generateSitemapXML(sitemapEntries) {
function generateSitemapXML(sitemapEntries) {
let xml = '<?xml version="1.0" encoding="UTF-8"?>\n';
xml += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n';
@@ -241,9 +239,9 @@
xml += "</urlset>";
return xml;
}
}
/**
/**
* Main sitemap generation function
*
* Combines document transformation and XML generation.
@@ -252,22 +250,22 @@
* @param {string} baseUrl - Base URL for the adapter
* @returns {string} Complete XML sitemap
*/
function generateSitemap(documents, baseUrl) {
function generateSitemap(documents, baseUrl) {
const entries = transformDocumentsToSitemapEntries(documents, baseUrl);
return generateSitemapXML(entries);
}
}
// =============================================================================
// Route Parsing
// =============================================================================
// =============================================================================
// Route Parsing
// =============================================================================
/**
/**
* Parse route from request
* @param {string} method - HTTP method
* @param {string} url - Request URL
* @returns {Object} Route info or error
*/
function parseRoute(method, url) {
function parseRoute(method, url) {
if (method !== "GET") {
return { route: null, error: "Method not allowed", statusCode: 405 };
}
@@ -280,36 +278,35 @@
return { route: "sitemap" };
}
// All other paths return 404
return { route: null, error: "Not found", statusCode: 404 };
}
// All other paths return 404
return { route: null, error: "Not found", statusCode: 404 };
}
// =============================================================================
// Return helpers object with all functions
// =============================================================================
// =============================================================================
// Return helpers object with all functions
// =============================================================================
return {
// Error classes
DocumentCountExceededError,
({
// Error classes
DocumentCountExceededError,
// Utilities
generateRequestId,
validateDocumentId,
validateDocumentCount,
// Utilities
generateRequestId,
validateDocumentId,
validateDocumentCount,
// XML
escapeXml,
// XML
escapeXml,
// Error mapping
mapDriveErrorToHttp,
// Error mapping
mapDriveErrorToHttp,
// Sitemap
toSitemapEntry,
transformDocumentsToSitemapEntries,
generateSitemapXML,
generateSitemap,
// Sitemap
toSitemapEntry,
transformDocumentsToSitemapEntries,
generateSitemapXML,
generateSitemap,
// Routing
parseRoute,
};
})();
// Routing
parseRoute,
});