### Run Server-Side Rendering Example Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/docs/development/getting-started.md Start the server-side rendering example and access it via http://localhost:8080 in your browser. ```bash npm start ``` -------------------------------- ### Run Example with MongoS3LibraryStorage Configuration Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-mongos3/docs/mongo-s3-library-storage.md Example command to start the Express application using MongoS3LibraryStorage by setting environment variables for MongoDB and S3 bucket. ```bash MONGODB_URL="mongodb://127.0.0.1:27017" MONGODB_DB=testdb1 MONGODB_USER=root MONGODB_PASSWORD=h5pnodejs LIBRARYSTORAGE=mongos3 LIBRARY_MONGO_COLLECTION=h5p LIBRARY_AWS_S3_BUCKET=h5plibrarybucket npm start ``` -------------------------------- ### Start Example Server with ClamAV Enabled Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-clamav-scanner/README.md Command to start the example server and enable ClamAV scanning. This environment variable is specific to the example code. ```sh CLAMSCAN_ENABLED=true npm start ``` -------------------------------- ### Run Example with MongoDB Storage Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-mongos3/docs/mongo-library-storage.md Configure and run the example Express application using MongoDB library storage by setting environment variables. This example demonstrates setting connection details and storage type. ```bash MONGODB_URL="mongodb://127.0.0.1:27017" MONGODB_DB=testdb1 MONGODB_USER=root MONGODB_PASSWORD=h5pnodejs LIBRARYSTORAGE=mongo LIBRARY_MONGO_COLLECTION=h5p npm start ``` -------------------------------- ### Start MongoDB and MinIO with Docker Compose Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-mongos3/docs/mongo-library-storage.md Use Docker Compose to start a MongoDB server and MinIO instance for development and testing. Ensure Docker and Docker Compose are installed. ```bash docker-compose -f scripts/mongo-s3-docker-compose.yml up -d ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/docs/development/getting-started.md Clone the repository and install all necessary dependencies for development. This includes linking cross-dependencies and downloading test assets. ```bash git clone https://github.com/lumieducation/h5p-nodejs-library cd h5p-nodejs-library npm install npm run setup ``` -------------------------------- ### Install @lumieducation/h5p-react Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-react/README.md Install the package using npm or yarn. ```sh $ npm install @lumieducation/h5p-react ``` -------------------------------- ### Install H5P Web Components Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-webcomponents/README.md Install the package using npm or yarn. This is the first step before importing and using the components in your project. ```sh npm install @lumieducation/h5p-webcomponents ``` -------------------------------- ### H5P Server loadContentCallback Example Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-webcomponents/README.md When using `@lumieducation/h5p-server`, implement `loadContentCallback` by utilizing `H5PPlayer.render`. This example shows how to set a renderer and then call `render` to obtain the player model, which should be sent to the client. ```typescript h5pPlayerOnServer.setRenderer(model => model); const playerModel = await h5pPlayerOnServer.render(contentId, user); // send playerModel to client and return it in loadContentCallback ``` -------------------------------- ### Install Vitest Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/ESM_MIGRATION_PLAN.md Install Vitest as a development dependency. This command should be run in the project's root directory. ```bash npm install -D vitest ``` -------------------------------- ### Example URL for Impersonation and Read-Only State Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/docs/advanced/impersonation.md Test impersonation and read-only state features by passing query parameters in the URL. This example demonstrates the format for the server-side-rendering example. ```url http://localhost:8080/h5p/play/?asUserId=&readOnlyState=yes ``` -------------------------------- ### Example Command for Running Express App with MongoS3 Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-mongos3/docs/mongo-s3-content-storage.md This command demonstrates how to configure and run the example Express application using MongoS3ContentStorage. It sets necessary environment variables for S3 and MongoDB connections, as well as content storage specifics. ```bash CONTENTSTORAGE=mongos3 AWS_ACCESS_KEY_ID=minioaccesskey AWS_SECRET_ACCESS_KEY=miniosecret AWS_S3_ENDPOINT="http://127.0.0.1:9000" MONGODB_URL="mongodb://127.0.0.1:27017" MONGODB_DB=testdb1 MONGODB_USER=root MONGODB_PASSWORD=h5pnodejs CONTENT_AWS_S3_BUCKET=testbucket1 CONTENT_MONGO_COLLECTION=h5p npm start ``` -------------------------------- ### Configure Example Application with S3 Storage Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-mongos3/docs/s3-temporary-file-storage.md Set environment variables to configure the example Express application to use S3 temporary storage. This includes specifying the storage type, bucket name, and S3 connection details. ```bash TEMPORARYSTORAGE=s3 AWS_ACCESS_KEY_ID=minioaccesskey AWS_SECRET_ACCESS_KEY=miniosecret AWS_S3_ENDPOINT="http://127.0.0.1:9000" TEMPORARY_AWS_S3_BUCKET=h5ptemporarybucket npm start ``` -------------------------------- ### H5P Editor Server loadContentCallback Setup Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-webcomponents/README.md Configure the H5P editor's server-side renderer to simply return the model when using `@lumieducation/h5p-server`. This setup is necessary for the `loadContentCallback` to function correctly when loading editor data. ```javascript h5pEditorOnServer.setRenderer(model => model); ``` -------------------------------- ### Install h5p-server package Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/docs/usage/integrating.md Add the h5p-server library to your project using npm. ```bash npm install @lumieducation/h5p-server ``` -------------------------------- ### Rebuild and Start H5P in Cluster Mode Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/docs/advanced/cluster.md Execute this command after making code changes that require a rebuild of the image. It starts 4 instances of h5p. ```bash docker-compose up --scale h5p=4 --build ``` -------------------------------- ### Import MongoS3LibraryStorage Components Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-mongos3/docs/mongo-s3-library-storage.md Import the necessary components for initializing MongoS3LibraryStorage. Ensure aws-sdk and mongodb are installed. ```typescript import { MongoS3LibraryStorage, initS3, initMongo } from '@lumieducation/h5p-mongos3'; ``` -------------------------------- ### Start H5P in Cluster Mode Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/docs/advanced/cluster.md Fires up 4 instances of h5p. Ensure you are in the directory containing the docker-compose.yml file. ```bash docker-compose up --scale h5p=4 ``` -------------------------------- ### Initialize FileLibraryStorage Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/docs/usage/h5p-editor-constructor.md Use `FileLibraryStorage` to manage installed libraries by specifying the directory where library information is stored. ```javascript const libraryStorage = new FileLibraryStorage(`h5p/libraries`); ``` -------------------------------- ### Build TypeScript Files Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/docs/development/getting-started.md Transpile TypeScript files to ES5. The TypeScript transpiler is automatically installed if you run `npm install`. ```bash npm run build ``` -------------------------------- ### Import MongoS3ContentStorage Components Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-mongos3/docs/mongo-s3-content-storage.md Import the necessary components for initializing MongoS3ContentStorage. Ensure these packages are installed. ```typescript import { MongoS3ContentStorage, initS3, initMongo } from '@lumieducation/h5p-mongos3'; ``` -------------------------------- ### Initialize FileContentStorage Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/docs/usage/h5p-editor-constructor.md Use `FileContentStorage` to manage installed content by specifying the directory where content information is stored. ```javascript const contentStorage = new FileContentStorage(`h5p/content`); ``` -------------------------------- ### Example Logic Check File Structure Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-shared-state-server/README.md A logic check file is an array of logic checks. All checks must pass for validation to succeed. This example demonstrates nested logical operators. ```json [ { "$or": [ { "$defined": { "$query": "$.create" } }, { "$and": [ { "$or": [ { "$.op[0].p": ["votesUp", 0] }, { "$.op[0].p": ["votesDown", 0] } ] }, { "$.op[0].li": { "$query": "$.context.user.id" } } ] }, { "$and": [ { "$.op[0].p": ["votesDown"] }, { "$.op[1].p": ["votesUp"] }, { "$.op[0].oi": [] }, { "$.op[1].oi": [] }, { "$.context.permission": "privileged" } ] } ] } ] ``` -------------------------------- ### Import MongoLibraryStorage and initMongo Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-mongos3/docs/mongo-library-storage.md Import the necessary components for using MongoLibraryStorage. Ensure the '@lumieducation/h5p-mongos3' package is installed. ```typescript import { MongoLibraryStorage, initMongo } from '@lumieducation/h5p-mongos3'; ``` -------------------------------- ### Import S3TemporaryFileStorage and initS3 Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-mongos3/docs/s3-temporary-file-storage.md Import the necessary components for S3 temporary file storage. Ensure you have the '@lumieducation/h5p-mongos3' package installed. ```typescript import { S3TemporaryFileStorage, initS3 } from '@lumieducation/h5p-mongos3'; ``` -------------------------------- ### Configure MathDisplay Addon Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/docs/advanced/addons.md Customize the behavior of the H5P.MathDisplay addon by setting the 'libraryConfig' property. This example shows how to configure observers and the MathJax renderer. ```javascript "libraryConfig": { "H5P.MathDisplay": { "observers": [ { "name": "mutationObserver", "params": { "cooldown": 500 } }, { "name": "domChangedListener" }, { "name": "interval", "params": { "time": 1000 } } ], "renderer": { "mathjax": { "src": "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js", "config": { "extensions": ["tex2jax.js"], "jax": ["input/TeX", "output/HTML-CSS"], "tex2jax": { "ignoreClass": "ckeditor", "processEscapes": true }, "messageStyle": "none" } } } } } ``` -------------------------------- ### Root package.json build scripts Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/ESM_MIGRATION_PLAN.md This example shows how the root `package.json` can invoke both ESM and CJS build scripts. It includes a `build:cjs` script that also calls a renaming script to handle `.js` to `.cjs` conversions. ```json { "scripts": { "build": "npm run build:esm && npm run build:cjs", "build:esm": "tsc -p tsconfig.build.esm.json", "build:cjs": "tsc -p tsconfig.build.cjs.json && node scripts/rename-cjs.js" } } ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/docs/development/getting-started.md Set the DEBUG environment variable to 'h5p:*' to view log messages. For verbose logs, also set LOG_LEVEL to 'debug'. This example is for Linux. ```bash DEBUG=h5p:* LOG_LEVEL=debug node script.js ``` -------------------------------- ### Addon Configuration for Content Regex Match Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/docs/advanced/addons.md Configure an addon to be added to content when a regex matches a string property. The regex must start and end with a slash. ```javascript { // ... more metadata ... "addTo": { "content": { "types": [ { "text": { "regex": "/your regex string/" // the regex string must start and end with a slash! } } ] } } // ... more metadata ... } ``` -------------------------------- ### Get Libraries Source: https://github.com/lumieducation/h5p-nodejs-library/wiki/AJAX-Endpoint Fetches detailed information about specific H5P libraries, including their semantics, language files, JavaScript and CSS dependencies, and translations. ```APIDOC ## GET /ajaxPath?action=libraries ### Description Retrieves detailed information for specified H5P libraries. ### Method GET ### Endpoint `/ajaxPath?action=libraries?machineName=&majorVersion=&minorVersion=` ### Parameters #### Query Parameters - **machineName** (string) - Required - The machine name of the library. - **majorVersion** (integer) - Required - The major version of the library. - **minorVersion** (integer) - Required - The minor version of the library. ### Response #### Success Response (200) - **semantics** (LibrarySemantics) - The semantic definition of the library. - **language** (LibraryLanguage) - The language files for the library. - **javascript** (Array) - An array of JavaScript dependencies. - **css** (Array) - An array of CSS dependencies. - **translation** (LibraryTranslation) - The translation files for the library. #### Response Example ```json { "semantics": {}, "language": {}, "javascript": [], "css": [], "translation": {} } ``` ``` -------------------------------- ### Launch Express.js Application Configuration Source: https://github.com/lumieducation/h5p-nodejs-library/wiki/sr258's-launch.json-file-for-VS-Code Configure VS Code to launch an Express.js application. This setup includes registering source map support and setting environment variables for debugging. ```json { "type": "node", "request": "launch", "name": "Launch Program", "program": "${workspaceFolder}/examples/express.js", "runtimeArgs": ["-r", "source-map-support/register"], "env": { "DEBUG": "h5p*" }, "outputCapture": "std", "console": "integratedTerminal" } ``` -------------------------------- ### Initializing H5P Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-webcomponents/README.md Demonstrates the initialization of H5P using its global namespace. This is a common pattern for setting up H5P functionality. ```typescript H5P.init(); // initialize H5P ``` -------------------------------- ### Install tsc-esm-fix for Post-Build Fix Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/ESM_MIGRATION_PLAN.md Install `tsc-esm-fix` as a development dependency to automatically add `.js` extensions to relative imports in your build output. ```bash npm install -D tsc-esm-fix ``` -------------------------------- ### Initialize H5P and Dispatch Events Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-react/README.md Demonstrates initializing the H5P library and setting up a listener for xAPI events. Ensure H5P is initialized before using external dispatchers. ```typescript H5P.init(); // initialize H5P H5P.externalDispatcher.on('xAPI', myCallback); const dialog = new H5P.Dialog(...); ``` -------------------------------- ### Build and Test Commands for H5P Node.js Library Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/CLAUDE.md Standard commands for building, testing, and formatting the H5P Node.js monorepo. Ensure 'h5p-server' is built first as other packages depend on it. ```bash npm run build npm run build:h5p-server npm test npm run test:h5p-mongos3 npm run test:integration npm run lint npm run format:check npm run format ``` -------------------------------- ### Get Content Type Cache Source: https://github.com/lumieducation/h5p-nodejs-library/wiki/AJAX-Endpoint Use this GET request to retrieve the content type cache, which shows the user's view of usable libraries. The response indicates if the cache is outdated and lists available libraries. ```http GET /ajaxPath?action=content-type-cache ``` ```typescript { "outdated": boolean, "libraries": Array } ``` -------------------------------- ### Minimal Local Library Cache Entry Source: https://github.com/lumieducation/h5p-nodejs-library/wiki/Communication-with-the-H5P-Hub This JSON structure defines the minimal data required for a library that is installed locally but not present in the H5P hub. It ensures that local libraries are correctly represented in the content type cache, including their versioning, installation status, and ownership. ```json { 'id': number, 'machineName': string, 'title': string, 'description': string, 'majorVersion': number, 'minorVersion': number, 'patchVersion': number, 'localMajorVersion': number, // same as majorVersion 'localMinorVersion': number, // same as minorVersion 'localPatchVersion': number, // same as patchVersion 'canInstall': false, 'installed': true, 'isUpToDate': true, 'owner': '', 'restricted': boolean, // depending on what is set in the local database 'icon': string // path to icon.svg } ``` -------------------------------- ### Import and instantiate H5PEditor Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/docs/usage/integrating.md Import the H5P library and instantiate the editor with configuration for storage, libraries, temporary files, and content. ```javascript import * as H5P from '@lumieducation/h5p-server'; const h5pEditor = H5P.fs( await new H5P.H5PConfig( new H5P.fsImplementations.JsonStorage( path.resolve('examples/config.json') // the path on the local disc // where the configuration file is stored ) ).load(), path.resolve('h5p/libraries'), // the path on the local disc where libraries // should be stored path.resolve('h5p/temporary-storage'), // the path on the local disc where // temporary files (uploads) should // be stored path.resolve('h5p/content') // the path on the local disc where content is // stored ); ``` -------------------------------- ### Content Initialization and Loading Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-webcomponents/README.md Explains how H5P components automatically load content from the server. It requires `loadContentCallback` and `content-id` to be set. The `content-id` can be set to 'new' to create new content. ```APIDOC ## Content Initialization and Loading The H5P components automatically (re-)load data from the server by calling `loadContentCallback`. This callback must be set as a property of the DOM element. The components will not work without this callback. Content is automatically loaded from the server after both of these conditions are fulfilled (in any order): 1. `loadContentCallback` is set. 2. `content-id` is set. You can change the value of `content-id` to discard old content and display new content. You can also safely remove the component from the DOM. To use the editor to create new content, set the `content-id` to the string `new`. **Caution:** If the newly created content is saved later, its `contentId` will be `undefined` in `saveContententCallback`, not `new`. ``` -------------------------------- ### Get Content Status API Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/content-hub.md Check the status of a content item in the H5P Content Hub. ```APIDOC ## GET /v1/contents//status ### Description Retrieves the current status of a content item in the H5P Content Hub. ### Method GET ### Endpoint https://hub-api.h5p.org/v1/contents//status ### Path Parameters - **id** (string) - Required - The unique identifier of the content. ### Headers - **Authorization** (string) - Required - The authorization token. - **Accept** (string) - Required - Specifies the expected response format, typically 'application/json'. ### Responses #### Success Response (200) Returns the status of the content. The status can be 1 (DOWNLOADED) or 2 (WAITING). ```json { "messages": { "info": ["string"], "error": [ { "message": "string", "code": "string" } ] }, "status": 1 | 2 } ``` #### Error Response (403) Returned if the request is forbidden. #### Other Error Responses Returned for other connection or server errors. ``` -------------------------------- ### Initialize Redis Lock Provider for H5P Server Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-redis-lock/README.md Demonstrates how to create a Redis client, connect it, instantiate the RedisLockProvider, and pass it to H5PEditor and H5PPlayer options. Ensure all H5PEditor instances use the same Redis database for the lock provider to prevent race conditions. ```typescript import { createClient } from '@redis/client'; import { H5PEditor, H5PPlayer } from '@lumieducation/h5p-server'; import RedisLockProvider from '@lumieducation/h5p-redis-lock'; // Create a regular redis connection const redisClient = createClient({ socket: { port, host, }, database }); try { await redisClient.connect(); } catch (error) { // handle error } // Create the lock provider const lockProvider = new RedisLockProvider(redisClient); // Pass it to the editor and player object const h5pEditor = new H5PEditor( /*other parameters*/, options: { lockProvider } ); const h5pPlayer = new H5PPlayer( /*other parameters*/, options: { lockProvider } ); ``` -------------------------------- ### H5P Plugin Update Content Function Source: https://github.com/lumieducation/h5p-nodejs-library/wiki/Saving-content Example of a plugin-specific function for updating existing H5P content. ```php framework->updateContent ``` -------------------------------- ### Run Tests with Vitest Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/ESM_MIGRATION_PLAN.md Execute the test suite using `npm run test` and related commands to verify the migration. Specific commands are provided for different test suites, including integration tests and those requiring Docker. ```bash npm run test npm run test:h5p-mongos3 # needs Docker: npm run start:dbs first npm run test:integration npm run lint npm run format:check ``` -------------------------------- ### Get Content by ID API Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/content-hub.md Retrieve specific content from the H5P Content Hub using its ID. ```APIDOC ## GET /v1/contents/ ### Description Retrieves a specific content item from the H5P Content Hub by its unique identifier. ### Method GET ### Endpoint https://hub-api.h5p.org/v1/contents/ ### Path Parameters - **id** (string) - Required - The unique identifier of the content to retrieve. ### Headers - **Authorization** (string) - Required - The authorization token for accessing the API. Format: 'Basic ' . base64_encode("$site_uuid:$hub_secret") - **Accept** (string) - Required - Specifies the expected response format, typically 'application/json'. ### Responses #### Success Response (200) Returns the requested content data. #### Error Response (404) Returned if the content with the specified ID is not found. #### Unauthorized Response Returned if the authorization token is invalid or missing, indicated by empty data in the response. ``` -------------------------------- ### Initialize MongoS3LibraryStorage Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-mongos3/docs/mongo-s3-library-storage.md Initialize the storage implementation with S3 and MongoDB configurations. Environment variables can be used for credentials and endpoints. ```typescript const storage = new MongoS3LibraryStorage( initS3({ credentials: { accessKeyId: 's3accesskey', // optional if env. variable is set secretAccessKey: 's3accesssecret' // optional if env. variable is set }, endpoint: 'http://127.0.0.1:9000', // optional if env. variable is set region: 'us-east-1', // optional if env. variable is set forcePathStyle: true }), ( await initMongo( 'mongodb://127.0.0.1:27017', // optional if env. variable is set 'testdb1', // optional if env. variable is set 'root', // optional if env. variable is set 'h5pnodejs' // optional if env. variable is set ) ).collection('h5p'), { s3Bucket: 'h5plibrarybucket' } ); await storage.createIndexes(); ``` -------------------------------- ### Run Project Tests Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/docs/development/testing-quality.md Execute the full test suite for the project. This command runs all tests, including integration tests. ```bash npm run test ``` -------------------------------- ### Get Account Information API Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/content-hub.md Retrieve account information for a given site UUID from the H5P Content Hub. ```APIDOC ## GET /v1/accounts/ ### Description Retrieves account information associated with a specific site UUID from the H5P Content Hub. ### Method GET ### Endpoint https://hub-api.h5p.org/v1/accounts/ ### Path Parameters - **siteUuid** (string) - Required - The unique identifier of the site. ### Headers - **Authorization** (string) - Required - The authorization token. - **Accept** (string) - Required - Specifies the expected response format, typically 'application/json'. ### Responses #### Success Response (200) Returns the account information. #### Error Responses - **401** - Unauthorized. - **Non-200 status codes** - Indicate connection or server errors. ``` -------------------------------- ### H5PPlayerUI - loadContentCallback Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-react/README.md Callback function to load H5P content data. It should retrieve data from the backend and return a promise resolving to an IPlayerModel. Errors should be thrown with a message property. ```APIDOC ## H5PPlayerUI loadContentCallback ### Description This callback function is responsible for retrieving the necessary data from the backend to load H5P content. It returns a promise that resolves to an object conforming to the `IPlayerModel` structure. If an error occurs during data retrieval, the callback should throw an error object with a `message` property. ### Method Signature ```ts loadContentCallback = async (contentId: string) => Promise; ``` ### Usage Example with @lumieducation/h5p-server ```js h5pPlayerOnServer.setRenderer((model) => model); const playerModel = await h5pPlayerOnServer.render(contentId, user); // send playerModel to client and return it in loadContentCallback ``` ### Error Handling Errors should be thrown as objects with a `message` property, e.g., `throw new Error('Failed to load content');` ``` -------------------------------- ### Import and Define H5P Components Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-webcomponents/README.md Import the H5P player and editor components and register them globally using `window.customElements.define`. Ensure these are called before the components are used in the DOM. ```javascript import { H5PPlayerComponent, H5PEditorComponent } from '@lumieducation/h5p-webcomponents'; window.customElements.define('h5p-player', H5PPlayerComponent); window.customElements.define('h5p-editor', H5PEditorComponent); ``` -------------------------------- ### Malware Scanning Configuration Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/docs/advanced/security.md This section explains how to integrate malware scanners into the H5P Editor setup by providing an array of scanner implementations. ```APIDOC ## Malware Scanning Configuration ### Description Malware scanners check uploaded user files for malicious content. If a scan is not positive, the H5P core library removes the files and returns an error. ### Usage Initialize the H5P Editor with the `malwareScanners` option: ```ts const h5pEditor = new H5PEditor( // ... regular configuration ... // Add the sanitizers to the options parameter { malwareScanners: [scanner1, scanner2] } ); ``` ### `IFileMalwareScanner` Interface Sanitizers must implement this interface: ```ts interface IFileMalwareScanner { /** The name of the scanner, e.g. ClamAV */ readonly name: string; /** Scans a file for malware and returns whether it contains malware. */ scan( file: string ): Promise<{ result: MalwareScanResult; viruses?: string }>; } enum MalwareScanResult { MalwareFound, Clean, NotScanned } ``` **Note:** Malware scanning requires uploaded content files to be passed as temporary files, not in-memory streams, to `H5PEditor.saveContentFile`. ``` -------------------------------- ### Implement Translation Callback Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/docs/usage/h5p-editor-constructor.md Provide a `translationCallbackAdapter` function to `H5PEditor` for localizing editor aspects. This example uses `i18NextTranslationFunction` and assumes `i18next` is configured. ```typescript // Pass translationCallbackAdapter as a parameter to H5PEditor. const translationCallbackAdapter = (key, language) => { return i18NextTranslationFunction(key, { lng: language }); }; ``` -------------------------------- ### Uninstall Jest Dependencies Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/ESM_MIGRATION_PLAN.md Remove Jest and its TypeScript transformer from development dependencies. Keep Jest installed temporarily if needed for existing scripts. ```bash npm uninstall ts-jest @types/jest ``` -------------------------------- ### Initialize H5P Editor with Malware Scanners Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/docs/advanced/security.md Configure the H5P Editor by passing an array of malware scanner instances to the `malwareScanners` option during initialization. Ensure scanners implement the `IFileMalwareScanner` interface. ```typescript const h5pEditor = new H5PEditor( // ... regular configuration ... // Add the sanitizers to the options parameter { malwareScanners: [scanner1, scanner2] } ); ``` -------------------------------- ### Update Type Casts for Vitest Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/ESM_MIGRATION_PLAN.md Adjust type casts from Jest-specific types to Vitest equivalents or generic `any`. For example, `as jest.Mocked` should become `as any` or `as Mocked<>` from Vitest. ```typescript as any ``` ```typescript as any ``` -------------------------------- ### Initialize ClamAV Scanner and H5PEditor Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-clamav-scanner/README.md Demonstrates how to create an instance of ClamAVScanner and integrate it into the H5PEditor configuration. Initialization is asynchronous. ```typescript import ClamAVScanner from '@lumieducation/clamav-scanner'; // There is no public constructor as the initialization is async. // That's why we have to use an async factory method. const clamAVScanner = await clamAVScanner.create(); const h5pEditor = new H5PEditor( // ... regular configuration ... // Add the scanner to the options parameter { malwareScanners: [ clamAVScanner ] } ); ``` -------------------------------- ### H5P Plugin Insert Content Function Source: https://github.com/lumieducation/h5p-nodejs-library/wiki/Saving-content Example of a plugin-specific function for inserting new H5P content, including database record saving and logging. ```php framework->insertContent ``` -------------------------------- ### Create H5P Components in JavaScript Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-webcomponents/README.md Instantiate H5P player and editor components programmatically using `document.createElement`. Set attributes and callbacks, then append them to the desired DOM element. ```javascript const h5pPlayer = document.createElement('h5p-player'); h5pPlayer.setAttribute('content-id', 'XXXX'); h5pPlayer.loadContentCallback = async (contentId) => { /** retrieve content model from server and return it as Promise **/ }; someOtherElement.appendChild(h5pPlayer); const h5pEditor = document.createElement('h5p-editor'); h5pEditor.setAttribute('content-id', 'XXXX'); h5pEditor.loadContentCallback = async (contentId) => { /** retrieve content model from server and return it as Promise **/ }; hpEditor.saveContentCallback = async (contentId, requestBody) => { /** save content on server **/ }; someOtherElement.appendChild(h5pEditor); ``` -------------------------------- ### Initialize MongoS3ContentStorage Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-mongos3/docs/mongo-s3-content-storage.md Instantiate MongoS3ContentStorage with S3 and MongoDB clients. Credentials and endpoints can be configured via environment variables or function parameters. The S3 bucket must be created manually. ```typescript const storage = new MongoS3ContentStorage( initS3({ credentials: { accessKeyId: 's3accesskey', // optional if env. variable is set secretAccessKey: 's3accesssecret' // optional if env. variable is set }, endpoint: 'http://127.0.0.1:9000', // optional if env. variable is set region: 'us-east-1', // optional if env. variable is set, forcePathStyle: true }), ( await initMongo( 'mongodb://127.0.0.1:27017', // optional if env. variable is set 'testdb1', // optional if env. variable is set 'root', // optional if env. variable is set 'h5pnodejs' // optional if env. variable is set ) ).collection('h5p'), { s3Bucket: 'h5pcontentbucket' } ); ``` -------------------------------- ### Integrating Customization Hooks into H5PEditor Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/docs/advanced/customization.md This example shows how to pass the custom semantic and language file alteration hooks to the H5PEditor constructor via the `customization` option. ```typescript const editor = new H5PEditor( cache, config, libraryStorage, contentStorage, translationCallback, // set to undefined if unneeded urlGenerator, // set to undefined if unneeded { customization: { alterLibraryLanguageFile: alterLibraryLanguageFileHook, alterLibrarySemantics: alterLibrarySemanticsHook } } ); ``` -------------------------------- ### Addon Configuration for Player Inclusion Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/docs/advanced/addons.md Configure an addon to be automatically added when loading the player for specified H5P types. This is a lumieducation extension and may change. ```javascript { // ... more metadata ... "addTo": { "player": [ "H5P.CoursePresentation", "H5P.InteractiveVideo" ] } // ... more metadata ... } ``` -------------------------------- ### Enabling User State with Express Router Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/docs/advanced/user-content-state.md If using `h5pAjaxExpressRouter`, the routes for the AJAX endpoint are automatically created. This example shows how to enable them by setting `routeContentUserData` in the options. ```javascript import express from "express"; import { h5pAjaxExpressRouter } from "@lumieducation/h5p-express"; const app = express(); // Assuming h5pExpressInstance is already configured const h5pExpressInstance = /* ... */; app.use("/h5p/ajax", h5pAjaxExpressRouter(h5pExpressInstance, { routeContentUserData: true })); ``` -------------------------------- ### Initialize S3TemporaryFileStorage Source: https://github.com/lumieducation/h5p-nodejs-library/blob/master/packages/h5p-mongos3/docs/s3-temporary-file-storage.md Instantiate S3TemporaryFileStorage with an initialized S3 client and bucket configuration. Credentials and endpoint can be provided directly or via environment variables. ```typescript const temporaryStorage = new S3TemporaryFileStorage( initS3({ credentials: { accessKeyId: 's3accesskey', // optional if env. variable is set secretAccessKey: 's3accesssecret' // optional if env. variable is set }, endpoint: 'http://127.0.0.1:9000', // optional if env. variable is set region: 'us-east-1' // optional if env. variable is set forcePathStyle: true }), { s3Bucket: 'h5ptemporarybucket' } ); ```