Used to check for browser translation.
用于检测浏览器翻译。
ブラウザの翻訳を検出する
Utilities

Environment & Config


This section details how to access Blocklet environment variables and SDK configuration settings, which are crucial for tailoring your Blocklet's behavior within the Blocklet Server ecosystem. Understanding these settings allows you to integrate seamlessly and respond to dynamic changes. For related utility functions, refer to the Utilities section.

Accessing Environment Variables#

The Blocklet SDK provides an env object that centralizes critical environment variables and application configurations. This object is populated from various sources, including system environment variables, Blocklet Server configurations, and component-specific settings.

env Object Properties#

The env object exposes properties essential for your Blocklet's operation:

Property Name

Type

Description

appId

string

The unique ID of the current Blocklet application.

appPid

string

The process ID of the current Blocklet application instance.

appIds

string[]

An array of IDs for all Blocklet applications.

appName

string

The user-friendly name of the Blocklet application.

appNameSlug

string

A URL-friendly slug of the application name.

appDescription

string

A brief description of the Blocklet application.

appUrl

string

The base URL where the Blocklet application is accessible.

isComponent

boolean

Indicates if the current Blocklet is running as a component.

dataDir

string

The directory path for persistent data storage.

cacheDir

string

The directory path for temporary cache data.

mode

string

The running mode of the Blocklet (e.g., development, production).

tenantMode

string

The tenant mode of the application.

appStorageEndpoint

string

The endpoint for application storage.

serverVersion

string

The version of the Blocklet Server.

sessionSalt

string

A salt used for session security.

languages

{ code: string; name: string; }[]

An array of supported languages for the Blocklet.

preferences

Record<string, any>

User preferences for the Blocklet.

componentDid

string

The DID of the current component, if applicable.

initialized

boolean

Indicates if the environment has been fully initialized.

Example: Accessing Environment Variables#

import { env } from '@blocklet/sdk';

const initializeApp = () => {
console.log(`Blocklet App ID: ${env.appId}`);
console.log(`Blocklet App Name: ${env.appName}`);
console.log(`Blocklet Server Version: ${env.serverVersion}`);
console.log(`Data Directory: ${env.dataDir}`);

if (env.isComponent) {
console.log(`Running as Component DID: ${env.componentDid}`);
}
};

initializeApp();

Managing Logger#

The SDK provides a flexible logger object for logging messages and a setLogger function to override the default console-based logger with a custom implementation.

logger Object#

The default logger object provides standard logging levels:

Method

Description

info(...args: any[])

Logs informational messages.

debug(...args: any[])

Logs debugging messages (only in development mode).

warn(...args: any[])

Logs warning messages.

error(...args: any[])

Logs error messages.

setLogger(newLogger)#

Allows you to replace the default logger with your own logging utility, which can integrate with external logging services or provide custom formatting.

Parameters

Name

Type

Description

newLogger

{ info: Function; debug: Function; warn: Function; error: Function; }

An object conforming to the logger interface.

Example: Using and Setting the Logger#

import { logger, setLogger } from '@blocklet/sdk';

// Using the default logger
logger.info('This is an info message from the SDK.');
logger.debug('This is a debug message, visible in development mode.');
logger.error('An error occurred!');

// Create a custom logger
const customLogger = {
info: (...args) => console.log('[CUSTOM INFO]', ...args),
debug: (...args) => console.log('[CUSTOM DEBUG]', ...args),
warn: (...args) => console.warn('[CUSTOM WARN]', ...args),
error: (...args) => console.error('[CUSTOM ERROR]', ...args),
};

// Set the custom logger
setLogger(customLogger);

// Now, messages will be logged using the custom logger
logger.info('This message now uses the custom logger.');

Dynamic Configuration Updates#

The env object and other Blocklet settings are designed to be reactive. The SDK listens for internal Blocklet Server events to automatically update its configuration and context, ensuring your Blocklet always has the most current information.

Key events that trigger updates include:

  • BlockletInternalEvents.appConfigChanged: Updates related to the main application's configuration.
  • BlockletInternalEvents.componentConfigChanged: Updates specific to the current component's configuration (e.g., decrypted environment variables).
  • BlockletInternalEvents.appSettingChanged: Generic application setting changes.

Upon these events, the SDK updates the env object and triggers refreshBlockletContext to fetch the latest __blocklet__.js and __blocklet__.json files, which can contain updated settings or runtime configurations for your Blocklet.

Your BlockletBlocklet SDKBlocklet ServerYour BlockletBlocklet SDKBlocklet ServerEmit appConfigChanged / componentConfigChanged_handleConfigUpdate / _handleComponentConfigUpdateenv object updatedTrigger refreshBlockletContextFetch __blocklet__.js / __blocklet__.jsonReturn updated JS/JSONUpdate blockletJs and blockletSettingsblocklet settings updated

Blocklet Server Version#

The SDK provides a ServerVersion utility to help your Blocklet adapt its behavior based on the Blocklet Server version it is running on. This is particularly useful for maintaining backward compatibility or leveraging new features available in specific server versions.

ServerVersion Instance#

The ServerVersion object is exposed directly from the SDK, allowing you to check the running Blocklet Server's version.

Property Name

Type

Description

version

string

The semantic version string of the Blocklet Server (e.g., '1.16.14').

Version Comparison Methods#

The ServerVersion object includes methods for convenient version comparison:

Method

Parameters

Description

gte(version: string)

version: The version string to compare against.

Returns true if the current server version is greater than or equal to the specified version.

gt(version: string)

version: The version string to compare against.

Returns true if the current server version is strictly greater than the specified version.

lte(version: string)

version: The version string to compare against.

Returns true if the current server version is less than or equal to the specified version.

lt(version: string)

version: The version string to compare against.

Returns true if the current server version is strictly less than the specified version.

Example: Checking Server Version#

import ServerVersion from '@blocklet/sdk/lib/util/server-version';

if (ServerVersion.gte('1.16.14')) {
console.log('Blocklet Server version is 1.16.14 or newer. Using new features.');
// Code that uses features available in 1.16.14+
} else {
console.log('Blocklet Server version is older than 1.16.14. Using fallback logic.');
// Code for older server versions
}

if (ServerVersion.lt('1.10.0')) {
console.warn('Running on a very old Blocklet Server version. Consider upgrading.');
}

console.log(`Current Blocklet Server version: ${ServerVersion.version}`);

Essential Environment Variables#

For a Blocklet to function correctly within the Blocklet Server environment, several critical environment variables are expected to be present. The SDK includes a checkBlockletEnvironment utility to verify their existence, throwing an error if any are missing. This ensures the Blocklet is running in a properly configured environment.

The following environment variables are essential:

  • BLOCKLET_APP_ID: The unique identifier for the Blocklet application.
  • BLOCKLET_APP_NAME: The name of the Blocklet application.
  • BLOCKLET_APP_DESCRIPTION: A description of the Blocklet application.
  • BLOCKLET_APP_SK: The secret key for the Blocklet application.
  • BLOCKLET_DID: The DID of the Blocklet itself.
  • ABT_NODE_DID: The DID of the Blocklet Server.
  • ABT_NODE_PK: The public key of the Blocklet Server.
  • ABT_NODE_PORT: The port on which the Blocklet Server is running.
  • ABT_NODE_SERVICE_PORT: The service port of the Blocklet Server.

Example: Checking Environment#

import checkBlockletEnvironment from '@blocklet/sdk/lib/util/check-blocklet-env';

try {
checkBlockletEnvironment();
console.log('All essential Blocklet environment variables are present.');
} catch (error) {
console.error(`Environment check failed: ${error.message}`);
process.exit(1); // Exit if essential environment variables are missing
}


This section provided a comprehensive overview of how to access and manage environment variables and configuration settings within the Blocklet SDK. You now understand how to retrieve crucial application details, control logging, and dynamically respond to configuration changes. Proceed to API Clients to learn about interacting with Blocklet Server APIs.