@twin.org/node-core 0.0.3-next.6 → 0.0.3-next.60
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/es/builders/engineEnvBuilder.js +538 -213
- package/dist/es/builders/engineEnvBuilder.js.map +1 -1
- package/dist/es/builders/engineServerEnvBuilder.js +86 -39
- package/dist/es/builders/engineServerEnvBuilder.js.map +1 -1
- package/dist/es/builders/extensionsBuilder.js +3 -3
- package/dist/es/builders/extensionsBuilder.js.map +1 -1
- package/dist/es/cli.js +254 -0
- package/dist/es/cli.js.map +1 -0
- package/dist/es/commands/bootstrapLegacy.js +311 -0
- package/dist/es/commands/bootstrapLegacy.js.map +1 -0
- package/dist/es/commands/help.js +86 -0
- package/dist/es/commands/help.js.map +1 -0
- package/dist/es/commands/identityCreate.js +377 -0
- package/dist/es/commands/identityCreate.js.map +1 -0
- package/dist/es/commands/identityImports.js +83 -0
- package/dist/es/commands/identityImports.js.map +1 -0
- package/dist/es/commands/identityVerifiableCredentialCreate.js +146 -0
- package/dist/es/commands/identityVerifiableCredentialCreate.js.map +1 -0
- package/dist/es/commands/identityVerificationMethodCreate.js +230 -0
- package/dist/es/commands/identityVerificationMethodCreate.js.map +1 -0
- package/dist/es/commands/identityVerificationMethodImport.js +127 -0
- package/dist/es/commands/identityVerificationMethodImport.js.map +1 -0
- package/dist/es/commands/nodeSetIdentity.js +69 -0
- package/dist/es/commands/nodeSetIdentity.js.map +1 -0
- package/dist/es/commands/removeTenantOrgAlias.js +83 -0
- package/dist/es/commands/removeTenantOrgAlias.js.map +1 -0
- package/dist/es/commands/setNodeOrgId.js +62 -0
- package/dist/es/commands/setNodeOrgId.js.map +1 -0
- package/dist/es/commands/setTenantOrgId.js +99 -0
- package/dist/es/commands/setTenantOrgId.js.map +1 -0
- package/dist/es/commands/tenantCreate.js +165 -0
- package/dist/es/commands/tenantCreate.js.map +1 -0
- package/dist/es/commands/tenantImport.js +108 -0
- package/dist/es/commands/tenantImport.js.map +1 -0
- package/dist/es/commands/tenantUpdate.js +108 -0
- package/dist/es/commands/tenantUpdate.js.map +1 -0
- package/dist/es/commands/userCreate.js +239 -0
- package/dist/es/commands/userCreate.js.map +1 -0
- package/dist/es/commands/userUpdate.js +154 -0
- package/dist/es/commands/userUpdate.js.map +1 -0
- package/dist/es/commands/vaultKeyCreate.js +191 -0
- package/dist/es/commands/vaultKeyCreate.js.map +1 -0
- package/dist/es/commands/vaultKeyImport.js +105 -0
- package/dist/es/commands/vaultKeyImport.js.map +1 -0
- package/dist/es/defaults.js +37 -2
- package/dist/es/defaults.js.map +1 -1
- package/dist/es/index.js +11 -4
- package/dist/es/index.js.map +1 -1
- package/dist/es/models/ICliArgs.js +4 -0
- package/dist/es/models/ICliArgs.js.map +1 -0
- package/dist/es/models/ICliCommand.js +2 -0
- package/dist/es/models/ICliCommand.js.map +1 -0
- package/dist/es/models/ICliCommandDefinition.js +2 -0
- package/dist/es/models/ICliCommandDefinition.js.map +1 -0
- package/dist/es/models/ICliCommandDefinitionParam.js +2 -0
- package/dist/es/models/ICliCommandDefinitionParam.js.map +1 -0
- package/dist/es/models/IEngineEnvironmentVariables.js.map +1 -1
- package/dist/es/models/IEngineServerEnvironmentVariables.js.map +1 -1
- package/dist/es/models/INodeEngineState.js.map +1 -1
- package/dist/es/models/INodeEnvironmentVariables.js.map +1 -1
- package/dist/es/models/INodeOptions.js.map +1 -1
- package/dist/es/models/cliCommandParamType.js +4 -0
- package/dist/es/models/cliCommandParamType.js.map +1 -0
- package/dist/es/models/nodeExtensionInitialiseEngineMethod.js +2 -0
- package/dist/es/models/nodeExtensionInitialiseEngineMethod.js.map +1 -0
- package/dist/es/models/nodeExtensionInitialiseEngineServerMethod.js +2 -0
- package/dist/es/models/nodeExtensionInitialiseEngineServerMethod.js.map +1 -0
- package/dist/es/models/nodeExtensionInitialiseMethod.js +2 -0
- package/dist/es/models/nodeExtensionInitialiseMethod.js.map +1 -0
- package/dist/es/models/nodeExtensionShutdownMethod.js +4 -0
- package/dist/es/models/nodeExtensionShutdownMethod.js.map +1 -0
- package/dist/es/node.js +87 -40
- package/dist/es/node.js.map +1 -1
- package/dist/es/start.js +189 -0
- package/dist/es/start.js.map +1 -0
- package/dist/es/utils.js +24 -27
- package/dist/es/utils.js.map +1 -1
- package/dist/types/builders/engineEnvBuilder.d.ts +60 -5
- package/dist/types/builders/engineServerEnvBuilder.d.ts +11 -2
- package/dist/types/builders/extensionsBuilder.d.ts +3 -3
- package/dist/types/cli.d.ts +56 -0
- package/dist/types/commands/bootstrapLegacy.d.ts +67 -0
- package/dist/types/commands/help.d.ts +24 -0
- package/dist/types/commands/identityCreate.d.ts +45 -0
- package/dist/types/commands/identityImports.d.ts +25 -0
- package/dist/types/commands/identityVerifiableCredentialCreate.d.ts +43 -0
- package/dist/types/commands/identityVerificationMethodCreate.d.ts +47 -0
- package/dist/types/commands/identityVerificationMethodImport.d.ts +32 -0
- package/dist/types/commands/nodeSetIdentity.d.ts +23 -0
- package/dist/types/commands/removeTenantOrgAlias.d.ts +24 -0
- package/dist/types/commands/setNodeOrgId.d.ts +24 -0
- package/dist/types/commands/setTenantOrgId.d.ts +38 -0
- package/dist/types/commands/tenantCreate.d.ts +41 -0
- package/dist/types/commands/tenantImport.d.ts +29 -0
- package/dist/types/commands/tenantUpdate.d.ts +29 -0
- package/dist/types/commands/userCreate.d.ts +51 -0
- package/dist/types/commands/userUpdate.d.ts +40 -0
- package/dist/types/commands/vaultKeyCreate.d.ts +43 -0
- package/dist/types/commands/vaultKeyImport.d.ts +29 -0
- package/dist/types/defaults.d.ts +30 -2
- package/dist/types/index.d.ts +11 -4
- package/dist/types/models/ICliArgs.d.ts +20 -0
- package/dist/types/models/ICliCommand.d.ts +17 -0
- package/dist/types/models/ICliCommandDefinition.d.ts +46 -0
- package/dist/types/models/ICliCommandDefinitionParam.d.ts +35 -0
- package/dist/types/models/IEngineEnvironmentVariables.d.ts +168 -95
- package/dist/types/models/IEngineServerEnvironmentVariables.d.ts +8 -0
- package/dist/types/models/INodeEngineState.d.ts +2 -9
- package/dist/types/models/INodeEnvironmentVariables.d.ts +0 -38
- package/dist/types/models/INodeOptions.d.ts +6 -2
- package/dist/types/models/cliCommandParamType.d.ts +4 -0
- package/dist/types/models/nodeExtensionInitialiseEngineMethod.d.ts +8 -0
- package/dist/types/models/nodeExtensionInitialiseEngineServerMethod.d.ts +9 -0
- package/dist/types/models/nodeExtensionInitialiseMethod.d.ts +9 -0
- package/dist/types/models/nodeExtensionShutdownMethod.d.ts +6 -0
- package/dist/types/node.d.ts +5 -4
- package/dist/types/{server.d.ts → start.d.ts} +4 -2
- package/dist/types/utils.d.ts +9 -10
- package/docs/changelog.md +675 -180
- package/docs/examples.md +99 -1
- package/docs/reference/functions/buildConfiguration.md +1 -1
- package/docs/reference/functions/buildEngineConfiguration.md +1 -7
- package/docs/reference/functions/buildEngineServerConfiguration.md +1 -1
- package/docs/reference/functions/constructCliCommand.md +27 -0
- package/docs/reference/functions/executeCommand.md +29 -0
- package/docs/reference/functions/extensionsInitialiseEngine.md +1 -1
- package/docs/reference/functions/extensionsInitialiseEngineServer.md +1 -1
- package/docs/reference/functions/getEnvDefaults.md +19 -0
- package/docs/reference/functions/getScriptDirectory.md +19 -0
- package/docs/reference/functions/initialiseLocales.md +2 -0
- package/docs/reference/functions/isAuthEntityStorageRequired.md +20 -0
- package/docs/reference/functions/isAutomationRequired.md +20 -0
- package/docs/reference/functions/isBackgroundTasksRequired.md +20 -0
- package/docs/reference/functions/isFederatedCatalogueRequired.md +20 -0
- package/docs/reference/functions/isImmutableProofRequired.md +20 -0
- package/docs/reference/functions/isRightsManagementRequired.md +23 -0
- package/docs/reference/functions/isTaskSchedulerRequired.md +20 -0
- package/docs/reference/functions/isTelemetryRequired.md +20 -0
- package/docs/reference/functions/isTrustRequired.md +20 -0
- package/docs/reference/functions/loadJsonFile.md +1 -1
- package/docs/reference/functions/loadTextFile.md +1 -1
- package/docs/reference/functions/parseCommandLineArgs.md +19 -0
- package/docs/reference/functions/processEnvOptions.md +27 -0
- package/docs/reference/functions/registerCommands.md +9 -0
- package/docs/reference/functions/resolvePackageEntryPoint.md +2 -2
- package/docs/reference/functions/run.md +8 -2
- package/docs/reference/functions/shutdownExtensions.md +1 -1
- package/docs/reference/functions/start.md +9 -3
- package/docs/reference/functions/substituteEnvOptions.md +25 -0
- package/docs/reference/index.md +24 -14
- package/docs/reference/interfaces/ICacheMetadata.md +3 -3
- package/docs/reference/interfaces/ICliArgs.md +35 -0
- package/docs/reference/interfaces/ICliCommand.md +23 -0
- package/docs/reference/interfaces/ICliCommandDefinition.md +101 -0
- package/docs/reference/interfaces/ICliCommandDefinitionParam.md +65 -0
- package/docs/reference/interfaces/IEngineEnvironmentVariables.md +488 -359
- package/docs/reference/interfaces/IEngineServerEnvironmentVariables.md +652 -431
- package/docs/reference/interfaces/IModuleProtocol.md +3 -3
- package/docs/reference/interfaces/INodeEngineState.md +6 -21
- package/docs/reference/interfaces/INodeEnvironmentVariables.md +661 -516
- package/docs/reference/interfaces/INodeOptions.md +44 -36
- package/docs/reference/interfaces/IProtocolHandlerResult.md +2 -2
- package/docs/reference/type-aliases/CliCommandParamType.md +5 -0
- package/docs/reference/type-aliases/NodeExtensionInitialiseEngineMethod.md +3 -1
- package/docs/reference/type-aliases/NodeExtensionInitialiseEngineServerMethod.md +3 -1
- package/docs/reference/type-aliases/NodeExtensionInitialiseMethod.md +3 -1
- package/docs/reference/type-aliases/NodeExtensionShutdownMethod.md +3 -1
- package/docs/reference/variables/ATTESTATION_VERIFICATION_METHOD_ID.md +2 -0
- package/docs/reference/variables/AUTH_SIGNING_KEY_ID.md +2 -0
- package/docs/reference/variables/BLOB_STORAGE_ENCRYPTION_KEY_ID.md +2 -0
- package/docs/reference/variables/CONTEXT_ID_HANDLER_FEATURE_DID.md +2 -0
- package/docs/reference/variables/CONTEXT_ID_HANDLER_FEATURE_TENANT.md +2 -0
- package/docs/reference/variables/IMMUTABLE_PROOF_VERIFICATION_METHOD_ID.md +2 -0
- package/docs/reference/variables/ModuleProtocol.md +5 -5
- package/docs/reference/variables/TRUST_VERIFICATION_METHOD_ID.md +5 -0
- package/locales/en.json +674 -30
- package/package.json +10 -6
- package/dist/es/bootstrap.js +0 -366
- package/dist/es/bootstrap.js.map +0 -1
- package/dist/es/identity.js +0 -182
- package/dist/es/identity.js.map +0 -1
- package/dist/es/models/nodeExtensionMethods.js +0 -2
- package/dist/es/models/nodeExtensionMethods.js.map +0 -1
- package/dist/es/models/nodeFeatures.js +0 -21
- package/dist/es/models/nodeFeatures.js.map +0 -1
- package/dist/es/server.js +0 -81
- package/dist/es/server.js.map +0 -1
- package/dist/types/bootstrap.d.ts +0 -68
- package/dist/types/identity.d.ts +0 -14
- package/dist/types/models/nodeExtensionMethods.d.ts +0 -27
- package/dist/types/models/nodeFeatures.d.ts +0 -21
- package/docs/detailed-guide.md +0 -129
- package/docs/reference/functions/bootstrap.md +0 -29
- package/docs/reference/functions/bootstrapAuth.md +0 -35
- package/docs/reference/functions/bootstrapBlobEncryption.md +0 -35
- package/docs/reference/functions/bootstrapImmutableProofMethod.md +0 -35
- package/docs/reference/functions/bootstrapNodeAdminUser.md +0 -35
- package/docs/reference/functions/bootstrapNodeId.md +0 -35
- package/docs/reference/functions/bootstrapSynchronisedStorage.md +0 -35
- package/docs/reference/functions/bootstrapTenantId.md +0 -35
- package/docs/reference/functions/getFeatures.md +0 -19
- package/docs/reference/type-aliases/NodeFeatures.md +0 -5
- package/docs/reference/variables/NodeFeatures.md +0 -25
- package/docs/reference/variables/SYNCHRONISED_STORAGE_BLOB_STORAGE_ENCRYPTION_KEY_ID.md +0 -3
- package/docs/reference/variables/VC_AUTHENTICATION_VERIFICATION_METHOD_ID.md +0 -3
package/dist/es/start.js
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { ContextIdKeys, ContextIdStore } from "@twin.org/context";
|
|
2
|
+
import { Coerce, ComponentFactory, GeneralError, I18n, Is } from "@twin.org/core";
|
|
3
|
+
import { Engine } from "@twin.org/engine";
|
|
4
|
+
import { FileStateStorage } from "@twin.org/engine-core";
|
|
5
|
+
import { EngineCoreFactory } from "@twin.org/engine-models";
|
|
6
|
+
import { EngineServer } from "@twin.org/engine-server";
|
|
7
|
+
import { BlobStorageConnectorType, EntityStorageConnectorType } from "@twin.org/engine-types";
|
|
8
|
+
import { extensionsInitialiseEngine, extensionsInitialiseEngineServer, shutdownExtensions } from "./builders/extensionsBuilder.js";
|
|
9
|
+
import { executeCommand } from "./cli.js";
|
|
10
|
+
/**
|
|
11
|
+
* Start the engine server.
|
|
12
|
+
* @param nodeOptions Optional run options for the engine server.
|
|
13
|
+
* @param nodeEngineConfig The configuration for the engine server.
|
|
14
|
+
* @param envVars The environment variables.
|
|
15
|
+
* @param cliCommand The constructed CLI command (optional).
|
|
16
|
+
* @param availableContextIdKeys The context ID keys available for operation.
|
|
17
|
+
* @returns The engine server.
|
|
18
|
+
*/
|
|
19
|
+
export async function start(nodeOptions, nodeEngineConfig, envVars, cliCommand, availableContextIdKeys) {
|
|
20
|
+
const entityStorageConnectorType = envVars.entityStorageConnectorType?.split(",") ?? [];
|
|
21
|
+
const blobStorageConnectorType = envVars.blobStorageConnectorType?.split(",") ?? [];
|
|
22
|
+
const requiresEngineStarted = cliCommand?.definition?.requiresEngineStarted ?? true;
|
|
23
|
+
const requiresNodeIdentity = cliCommand?.definition?.requiresNodeIdentity ?? true;
|
|
24
|
+
const requiresOrgIdentity = cliCommand?.definition?.requiresOrgIdentity ?? true;
|
|
25
|
+
// File connectors (blob/entity) and the default file-based state storage all
|
|
26
|
+
// persist to disk under storageFileRoot, so it must be set when any of them is in use.
|
|
27
|
+
if ((entityStorageConnectorType.includes(EntityStorageConnectorType.File) ||
|
|
28
|
+
blobStorageConnectorType.includes(BlobStorageConnectorType.File) ||
|
|
29
|
+
Is.empty(nodeOptions?.stateStorage)) &&
|
|
30
|
+
!Is.stringValue(envVars.storageFileRoot) &&
|
|
31
|
+
requiresEngineStarted) {
|
|
32
|
+
throw new GeneralError("node", "storageFileRootNotSet", {
|
|
33
|
+
storageFileRoot: `${nodeOptions?.envPrefix ?? ""}STORAGE_FILE_ROOT`
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
// Create the engine instance using file state storage unless one is configured in options
|
|
37
|
+
const engine = new Engine({
|
|
38
|
+
config: nodeEngineConfig,
|
|
39
|
+
stateStorage: requiresEngineStarted
|
|
40
|
+
? (nodeOptions?.stateStorage ?? new FileStateStorage(envVars.stateFilename ?? ""))
|
|
41
|
+
: undefined,
|
|
42
|
+
customBootstrap: async (engineCore) => {
|
|
43
|
+
configureContextIds(engineCore, envVars, requiresEngineStarted, requiresNodeIdentity, requiresOrgIdentity);
|
|
44
|
+
if (!Is.objectValue(cliCommand) && requiresEngineStarted) {
|
|
45
|
+
await ContextIdStore.run(engineCore.getContextIds() ?? {}, async () => {
|
|
46
|
+
await enforceTenantOrganizationIds(engineCore, envVars);
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
configureContextIdKeys(engine, availableContextIdKeys);
|
|
52
|
+
// Construct the server with the engine.
|
|
53
|
+
const server = new EngineServer({ engineCore: engine });
|
|
54
|
+
// Extend the engine.
|
|
55
|
+
if (Is.function(nodeOptions?.extendEngine)) {
|
|
56
|
+
await engine.logInfo(I18n.formatMessage("node.extendingEngine"));
|
|
57
|
+
await nodeOptions.extendEngine(engine);
|
|
58
|
+
}
|
|
59
|
+
await extensionsInitialiseEngine(envVars, engine);
|
|
60
|
+
// Extend the engine server.
|
|
61
|
+
if (Is.function(nodeOptions?.extendEngineServer)) {
|
|
62
|
+
await engine.logInfo(I18n.formatMessage("node.extendingEngineServer"));
|
|
63
|
+
await nodeOptions?.extendEngineServer(server);
|
|
64
|
+
}
|
|
65
|
+
await extensionsInitialiseEngineServer(envVars, engine, server);
|
|
66
|
+
// Need to register the engine with the factory so that background tasks
|
|
67
|
+
// can clone it to spawn new instances.
|
|
68
|
+
EngineCoreFactory.register("engine", () => engine);
|
|
69
|
+
if (Is.objectValue(cliCommand)) {
|
|
70
|
+
await executeCommand(engine, envVars, cliCommand);
|
|
71
|
+
}
|
|
72
|
+
else {
|
|
73
|
+
try {
|
|
74
|
+
// Start the server, which also starts the engine.
|
|
75
|
+
await server.start();
|
|
76
|
+
return {
|
|
77
|
+
engine,
|
|
78
|
+
server,
|
|
79
|
+
shutdown: async () => {
|
|
80
|
+
await shutdownExtensions(envVars, engine);
|
|
81
|
+
await server.stop();
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
catch (err) {
|
|
86
|
+
await shutdownExtensions(envVars, engine);
|
|
87
|
+
throw err;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Populate the engine context IDs from the current engine state.
|
|
93
|
+
* @param engine The engine to configure.
|
|
94
|
+
* @param envVars The environment variables.
|
|
95
|
+
* @param requiresEngineStarted Whether the engine is required to be started.
|
|
96
|
+
* @param requiresNodeIdentity Whether the node identity is required.
|
|
97
|
+
* @param requiresOrgIdentity Whether the organization identity is required.
|
|
98
|
+
* @throws GeneralError if the node identity or organization ID is required but not set.
|
|
99
|
+
*/
|
|
100
|
+
function configureContextIds(engine, envVars, requiresEngineStarted, requiresNodeIdentity, requiresOrgIdentity) {
|
|
101
|
+
const state = engine.getState();
|
|
102
|
+
if (requiresEngineStarted) {
|
|
103
|
+
if (Is.stringValue(state.nodeId)) {
|
|
104
|
+
engine.addContextId(ContextIdKeys.Node, state.nodeId);
|
|
105
|
+
}
|
|
106
|
+
else if (requiresNodeIdentity) {
|
|
107
|
+
throw new GeneralError("node", "nodeIdentityNotSet");
|
|
108
|
+
}
|
|
109
|
+
const tenantEnabled = Coerce.boolean(envVars.tenantEnabled) ?? false;
|
|
110
|
+
if (!tenantEnabled) {
|
|
111
|
+
if (Is.stringValue(state.nodeOrganizationId)) {
|
|
112
|
+
engine.addContextId(ContextIdKeys.Organization, state.nodeOrganizationId);
|
|
113
|
+
}
|
|
114
|
+
else if (requiresOrgIdentity) {
|
|
115
|
+
throw new GeneralError("node", "nodeOrganizationIdNotSet");
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Configure the available context ID keys on the engine.
|
|
122
|
+
* @param engine The engine to configure.
|
|
123
|
+
* @param availableContextIdKeys The available context ID keys.
|
|
124
|
+
*/
|
|
125
|
+
function configureContextIdKeys(engine, availableContextIdKeys) {
|
|
126
|
+
if (Is.arrayValue(availableContextIdKeys)) {
|
|
127
|
+
const added = [];
|
|
128
|
+
for (const availableContextIdKey of availableContextIdKeys) {
|
|
129
|
+
if (!added.includes(availableContextIdKey.key)) {
|
|
130
|
+
engine.addContextIdKey(availableContextIdKey.key, availableContextIdKey.requiredHandlerFeatures);
|
|
131
|
+
added.push(availableContextIdKey.key);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Scan all tenants for a missing organization ID.
|
|
138
|
+
* If exactly one tenant is missing and the node's own organization ID is available in state,
|
|
139
|
+
* the value is automatically applied and persisted (legacy migration path).
|
|
140
|
+
* If multiple tenants are missing, or the single missing tenant cannot be auto-recovered,
|
|
141
|
+
* startup is blocked with an error listing the affected tenant IDs.
|
|
142
|
+
* @param engineCore The engine core.
|
|
143
|
+
* @param envVars The environment variables.
|
|
144
|
+
* @returns A promise that resolves when all tenants have valid organization IDs.
|
|
145
|
+
* @throws GeneralError if multiple tenants are missing their organization ID and cannot be auto-recovered.
|
|
146
|
+
*/
|
|
147
|
+
async function enforceTenantOrganizationIds(engineCore, envVars) {
|
|
148
|
+
const tenantEnabled = Coerce.boolean(envVars.tenantEnabled) ?? false;
|
|
149
|
+
if (!tenantEnabled) {
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
const type = engineCore.getRegisteredInstanceTypeOptional("tenantAdminComponent");
|
|
153
|
+
if (!Is.stringValue(type)) {
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
const tenantAdminComponent = ComponentFactory.get(type);
|
|
157
|
+
const missingIds = [];
|
|
158
|
+
let cursor;
|
|
159
|
+
do {
|
|
160
|
+
const { tenants, cursor: next } = await tenantAdminComponent.query(undefined, ["id", "organizationId"], cursor);
|
|
161
|
+
for (const tenant of tenants) {
|
|
162
|
+
if (Is.stringValue(tenant.id) && !Is.stringValue(tenant.organizationId)) {
|
|
163
|
+
missingIds.push(tenant.id);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
cursor = next;
|
|
167
|
+
} while (Is.stringValue(cursor));
|
|
168
|
+
if (missingIds.length === 0) {
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
if (missingIds.length === 1) {
|
|
172
|
+
const state = engineCore.getState();
|
|
173
|
+
if (Is.stringValue(state.nodeOrganizationId)) {
|
|
174
|
+
engineCore.logInfo(I18n.formatMessage("node.tenantOrganizationIdAutoAssigned", {
|
|
175
|
+
tenantId: missingIds[0],
|
|
176
|
+
organizationId: state.nodeOrganizationId
|
|
177
|
+
}));
|
|
178
|
+
await tenantAdminComponent.update({
|
|
179
|
+
id: missingIds[0],
|
|
180
|
+
organizationId: state.nodeOrganizationId
|
|
181
|
+
});
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
throw new GeneralError("node", "tenantsWithoutOrganizationId", {
|
|
186
|
+
tenantIds: missingIds.join(", ")
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
//# sourceMappingURL=start.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"start.js","sourceRoot":"","sources":["../../src/start.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAClE,OAAO,EAAE,MAAM,EAAE,g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C7B,OAAO;IACR,CAAC;IAED,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC7B,MAAM,KAAK,GAAG,UAAU,CAAC,QAAQ,EAAE,CAAC;QACpC,IAAI,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,kBAAkB,CAAC,EAAE,CAAC;YAC9C,UAAU,CAAC,OAAO,CACjB,IAAI,CAAC,aAAa,CAAC,uCAAuC,EAAE;gBAC3D,QAAQ,EAAE,UAAU,CAAC,CAAC,CAAC;gBACvB,cAAc,EAAE,KAAK,CAAC,kBAAkB;aACxC,CAAC,CACF,CAAC;YACF,MAAM,oBAAoB,CAAC,MAAM,CAAC;gBACjC,EAAE,EAAE,UAAU,CAAC,CAAC,CAAC;gBACjB,cAAc,EAAE,KAAK,CAAC,kBAAkB;aACxC,CAAC,CAAC;YACH,OAAO;QACR,CAAC;IACF,CAAC;IAED,MAAM,IAAI,YAAY,CAAC,MAAM,EAAE,8BAA8B,EAAE;QAC9D,SAAS,EAAE,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC;KAChC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { ITenantAdminComponent } from \"@twin.org/api-models\";\nimport { ContextIdKeys, ContextIdStore } from \"@twin.org/context\";\nimport { Coerce, ComponentFactory, GeneralError, I18n, Is } from \"@twin.org/core\";\nimport { Engine } from \"@twin.org/engine\";\nimport { FileStateStorage } from \"@twin.org/engine-core\";\nimport {\n\tEngineCoreFactory,\n\ttype IEngineCore,\n\ttype IEngineCoreConfig\n} from \"@twin.org/engine-models\";\nimport { EngineServer } from \"@twin.org/engine-server\";\nimport type { IEngineServerConfig } from \"@twin.org/engine-server-types\";\nimport { BlobStorageConnectorType, EntityStorageConnectorType } from \"@twin.org/engine-types\";\nimport {\n\textensionsInitialiseEngine,\n\textensionsInitialiseEngineServer,\n\tshutdownExtensions\n} from \"./builders/extensionsBuilder.js\";\nimport { executeCommand } from \"./cli.js\";\nimport type { ICliCommand } from \"./models/ICliCommand.js\";\nimport type { INodeEngineConfig } from \"./models/INodeEngineConfig.js\";\nimport type { INodeEngineState } from \"./models/INodeEngineState.js\";\nimport type { INodeEnvironmentVariables } from \"./models/INodeEnvironmentVariables.js\";\nimport type { INodeOptions } from \"./models/INodeOptions.js\";\n\n/**\n * Start the engine server.\n * @param nodeOptions Optional run options for the engine server.\n * @param nodeEngineConfig The configuration for the engine server.\n * @param envVars The environment variables.\n * @param cliCommand The constructed CLI command (optional).\n * @param availableContextIdKeys The context ID keys available for operation.\n * @returns The engine server.\n */\nexport async function start(\n\tnodeOptions: INodeOptions | undefined,\n\tnodeEngineConfig: INodeEngineConfig,\n\tenvVars: INodeEnvironmentVariables,\n\tcliCommand?: ICliCommand,\n\tavailableContextIdKeys?: { key: string; requiredHandlerFeatures: string[] }[]\n): Promise<\n\t| {\n\t\t\tengine: Engine<IEngineServerConfig, INodeEngineState>;\n\t\t\tserver: EngineServer;\n\t\t\tshutdown: () => Promise<void>;\n\t }\n\t| undefined\n> {\n\tconst entityStorageConnectorType = envVars.entityStorageConnectorType?.split(\",\") ?? [];\n\tconst blobStorageConnectorType = envVars.blobStorageConnectorType?.split(\",\") ?? [];\n\n\tconst requiresEngineStarted = cliCommand?.definition?.requiresEngineStarted ?? true;\n\tconst requiresNodeIdentity = cliCommand?.definition?.requiresNodeIdentity ?? true;\n\tconst requiresOrgIdentity = cliCommand?.definition?.requiresOrgIdentity ?? true;\n\n\t// File connectors (blob/entity) and the default file-based state storage all\n\t// persist to disk under storageFileRoot, so it must be set when any of them is in use.\n\tif (\n\t\t(entityStorageConnectorType.includes(EntityStorageConnectorType.File) ||\n\t\t\tblobStorageConnectorType.includes(BlobStorageConnectorType.File) ||\n\t\t\tIs.empty(nodeOptions?.stateStorage)) &&\n\t\t!Is.stringValue(envVars.storageFileRoot) &&\n\t\trequiresEngineStarted\n\t) {\n\t\tthrow new GeneralError(\"node\", \"storageFileRootNotSet\", {\n\t\t\tstorageFileRoot: `${nodeOptions?.envPrefix ?? \"\"}STORAGE_FILE_ROOT`\n\t\t});\n\t}\n\n\t// Create the engine instance using file state storage unless one is configured in options\n\tconst engine = new Engine<IEngineServerConfig, INodeEngineState>({\n\t\tconfig: nodeEngineConfig,\n\t\tstateStorage: requiresEngineStarted\n\t\t\t? (nodeOptions?.stateStorage ?? new FileStateStorage(envVars.stateFilename ?? \"\"))\n\t\t\t: undefined,\n\t\tcustomBootstrap: async engineCore => {\n\t\t\tconfigureContextIds(\n\t\t\t\tengineCore,\n\t\t\t\tenvVars,\n\t\t\t\trequiresEngineStarted,\n\t\t\t\trequiresNodeIdentity,\n\t\t\t\trequiresOrgIdentity\n\t\t\t);\n\t\t\tif (!Is.objectValue(cliCommand) && requiresEngineStarted) {\n\t\t\t\tawait ContextIdStore.run(engineCore.getContextIds() ?? {}, async () => {\n\t\t\t\t\tawait enforceTenantOrganizationIds(engineCore, envVars);\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t});\n\n\tconfigureContextIdKeys(engine, availableContextIdKeys);\n\n\t// Construct the server with the engine.\n\tconst server = new EngineServer({ engineCore: engine });\n\n\t// Extend the engine.\n\tif (Is.function(nodeOptions?.extendEngine)) {\n\t\tawait engine.logInfo(I18n.formatMessage(\"node.extendingEngine\"));\n\t\tawait nodeOptions.extendEngine(engine);\n\t}\n\n\tawait extensionsInitialiseEngine(envVars, engine);\n\n\t// Extend the engine server.\n\tif (Is.function(nodeOptions?.extendEngineServer)) {\n\t\tawait engine.logInfo(I18n.formatMessage(\"node.extendingEngineServer\"));\n\t\tawait nodeOptions?.extendEngineServer(server);\n\t}\n\n\tawait extensionsInitialiseEngineServer(envVars, engine, server);\n\n\t// Need to register the engine with the factory so that background tasks\n\t// can clone it to spawn new instances.\n\tEngineCoreFactory.register(\"engine\", () => engine);\n\n\tif (Is.objectValue(cliCommand)) {\n\t\tawait executeCommand(engine, envVars, cliCommand);\n\t} else {\n\t\ttry {\n\t\t\t// Start the server, which also starts the engine.\n\t\t\tawait server.start();\n\n\t\t\treturn {\n\t\t\t\tengine,\n\t\t\t\tserver,\n\t\t\t\tshutdown: async () => {\n\t\t\t\t\tawait shutdownExtensions(envVars, engine);\n\t\t\t\t\tawait server.stop();\n\t\t\t\t}\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tawait shutdownExtensions(envVars, engine);\n\t\t\tthrow err;\n\t\t}\n\t}\n}\n\n/**\n * Populate the engine context IDs from the current engine state.\n * @param engine The engine to configure.\n * @param envVars The environment variables.\n * @param requiresEngineStarted Whether the engine is required to be started.\n * @param requiresNodeIdentity Whether the node identity is required.\n * @param requiresOrgIdentity Whether the organization identity is required.\n * @throws GeneralError if the node identity or organization ID is required but not set.\n */\nfunction configureContextIds(\n\tengine: IEngineCore<IEngineCoreConfig, INodeEngineState>,\n\tenvVars: INodeEnvironmentVariables,\n\trequiresEngineStarted: boolean,\n\trequiresNodeIdentity: boolean,\n\trequiresOrgIdentity: boolean\n): void {\n\tconst state = engine.getState();\n\n\tif (requiresEngineStarted) {\n\t\tif (Is.stringValue(state.nodeId)) {\n\t\t\tengine.addContextId(ContextIdKeys.Node, state.nodeId);\n\t\t} else if (requiresNodeIdentity) {\n\t\t\tthrow new GeneralError(\"node\", \"nodeIdentityNotSet\");\n\t\t}\n\n\t\tconst tenantEnabled = Coerce.boolean(envVars.tenantEnabled) ?? false;\n\t\tif (!tenantEnabled) {\n\t\t\tif (Is.stringValue(state.nodeOrganizationId)) {\n\t\t\t\tengine.addContextId(ContextIdKeys.Organization, state.nodeOrganizationId);\n\t\t\t} else if (requiresOrgIdentity) {\n\t\t\t\tthrow new GeneralError(\"node\", \"nodeOrganizationIdNotSet\");\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Configure the available context ID keys on the engine.\n * @param engine The engine to configure.\n * @param availableContextIdKeys The available context ID keys.\n */\nfunction configureContextIdKeys(\n\tengine: IEngineCore<IEngineCoreConfig, INodeEngineState>,\n\tavailableContextIdKeys: { key: string; requiredHandlerFeatures: string[] }[] | undefined\n): void {\n\tif (Is.arrayValue(availableContextIdKeys)) {\n\t\tconst added: string[] = [];\n\t\tfor (const availableContextIdKey of availableContextIdKeys) {\n\t\t\tif (!added.includes(availableContextIdKey.key)) {\n\t\t\t\tengine.addContextIdKey(\n\t\t\t\t\tavailableContextIdKey.key,\n\t\t\t\t\tavailableContextIdKey.requiredHandlerFeatures\n\t\t\t\t);\n\t\t\t\tadded.push(availableContextIdKey.key);\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Scan all tenants for a missing organization ID.\n * If exactly one tenant is missing and the node's own organization ID is available in state,\n * the value is automatically applied and persisted (legacy migration path).\n * If multiple tenants are missing, or the single missing tenant cannot be auto-recovered,\n * startup is blocked with an error listing the affected tenant IDs.\n * @param engineCore The engine core.\n * @param envVars The environment variables.\n * @returns A promise that resolves when all tenants have valid organization IDs.\n * @throws GeneralError if multiple tenants are missing their organization ID and cannot be auto-recovered.\n */\nasync function enforceTenantOrganizationIds(\n\tengineCore: IEngineCore<IEngineCoreConfig, INodeEngineState>,\n\tenvVars: INodeEnvironmentVariables\n): Promise<void> {\n\tconst tenantEnabled = Coerce.boolean(envVars.tenantEnabled) ?? false;\n\tif (!tenantEnabled) {\n\t\treturn;\n\t}\n\n\tconst type = engineCore.getRegisteredInstanceTypeOptional(\"tenantAdminComponent\");\n\tif (!Is.stringValue(type)) {\n\t\treturn;\n\t}\n\n\tconst tenantAdminComponent = ComponentFactory.get<ITenantAdminComponent>(type);\n\tconst missingIds: string[] = [];\n\tlet cursor: string | undefined;\n\n\tdo {\n\t\tconst { tenants, cursor: next } = await tenantAdminComponent.query(\n\t\t\tundefined,\n\t\t\t[\"id\", \"organizationId\"],\n\t\t\tcursor\n\t\t);\n\t\tfor (const tenant of tenants) {\n\t\t\tif (Is.stringValue(tenant.id) && !Is.stringValue(tenant.organizationId)) {\n\t\t\t\tmissingIds.push(tenant.id);\n\t\t\t}\n\t\t}\n\t\tcursor = next;\n\t} while (Is.stringValue(cursor));\n\n\tif (missingIds.length === 0) {\n\t\treturn;\n\t}\n\n\tif (missingIds.length === 1) {\n\t\tconst state = engineCore.getState();\n\t\tif (Is.stringValue(state.nodeOrganizationId)) {\n\t\t\tengineCore.logInfo(\n\t\t\t\tI18n.formatMessage(\"node.tenantOrganizationIdAutoAssigned\", {\n\t\t\t\t\ttenantId: missingIds[0],\n\t\t\t\t\torganizationId: state.nodeOrganizationId\n\t\t\t\t})\n\t\t\t);\n\t\t\tawait tenantAdminComponent.update({\n\t\t\t\tid: missingIds[0],\n\t\t\t\torganizationId: state.nodeOrganizationId\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t}\n\n\tthrow new GeneralError(\"node\", \"tenantsWithoutOrganizationId\", {\n\t\ttenantIds: missingIds.join(\", \")\n\t});\n}\n"]}
|
package/dist/es/utils.js
CHANGED
|
@@ -9,10 +9,10 @@ import { BaseError, Converter, GeneralError, I18n, Is } from "@twin.org/core";
|
|
|
9
9
|
import { Sha256 } from "@twin.org/crypto";
|
|
10
10
|
import { ModuleHelper } from "@twin.org/modules";
|
|
11
11
|
import { ModuleProtocol } from "./models/moduleProtocol.js";
|
|
12
|
-
import { NodeFeatures } from "./models/nodeFeatures.js";
|
|
13
12
|
/**
|
|
14
13
|
* Initialise the locales for the application.
|
|
15
14
|
* @param localesDirectory The directory containing the locales.
|
|
15
|
+
* @returns A promise that resolves when the locale dictionary has been loaded.
|
|
16
16
|
*/
|
|
17
17
|
export async function initialiseLocales(localesDirectory) {
|
|
18
18
|
const localesFile = path.resolve(path.join(localesDirectory, "en.json"));
|
|
@@ -32,6 +32,17 @@ export async function initialiseLocales(localesDirectory) {
|
|
|
32
32
|
export function getExecutionDirectory() {
|
|
33
33
|
return process.cwd();
|
|
34
34
|
}
|
|
35
|
+
/**
|
|
36
|
+
* Get the directory where the script is located.
|
|
37
|
+
* @param args The command line arguments.
|
|
38
|
+
* @returns The directory containing the entry-point script, or the current working directory if not determinable.
|
|
39
|
+
*/
|
|
40
|
+
export function getScriptDirectory(args) {
|
|
41
|
+
if (Is.array(args) && args.length >= 2 && args[1].includes("index.js")) {
|
|
42
|
+
return path.resolve(path.join(path.dirname(args[1]), ".."));
|
|
43
|
+
}
|
|
44
|
+
return process.cwd();
|
|
45
|
+
}
|
|
35
46
|
/**
|
|
36
47
|
* Does the specified file exist.
|
|
37
48
|
* @param filename The filename to check for existence.
|
|
@@ -107,7 +118,7 @@ export async function getFiles(directory) {
|
|
|
107
118
|
/**
|
|
108
119
|
* Load the text file.
|
|
109
120
|
* @param filename The filename of the text file to load.
|
|
110
|
-
* @returns The contents of the text file
|
|
121
|
+
* @returns The contents of the text file as a UTF-8 string.
|
|
111
122
|
*/
|
|
112
123
|
export async function loadTextFile(filename) {
|
|
113
124
|
return readFile(filename, "utf8");
|
|
@@ -115,32 +126,12 @@ export async function loadTextFile(filename) {
|
|
|
115
126
|
/**
|
|
116
127
|
* Load the JSON file.
|
|
117
128
|
* @param filename The filename of the JSON file to load.
|
|
118
|
-
* @returns The
|
|
129
|
+
* @returns The parsed JSON content of the file.
|
|
119
130
|
*/
|
|
120
131
|
export async function loadJsonFile(filename) {
|
|
121
132
|
const content = await loadTextFile(filename);
|
|
122
133
|
return JSON.parse(content);
|
|
123
134
|
}
|
|
124
|
-
/**
|
|
125
|
-
* Get the features that are enabled on the node.
|
|
126
|
-
* @param env The environment variables for the node.
|
|
127
|
-
* @returns The features that are enabled on the node.
|
|
128
|
-
*/
|
|
129
|
-
export function getFeatures(env) {
|
|
130
|
-
if (Is.empty(env.features)) {
|
|
131
|
-
return [];
|
|
132
|
-
}
|
|
133
|
-
const features = [];
|
|
134
|
-
const allFeatures = Object.values(NodeFeatures);
|
|
135
|
-
const splitFeatures = env.features.split(",");
|
|
136
|
-
for (const feature of splitFeatures) {
|
|
137
|
-
const featureTrimmed = feature.trim();
|
|
138
|
-
if (allFeatures.includes(featureTrimmed)) {
|
|
139
|
-
features.push(featureTrimmed);
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
return features;
|
|
143
|
-
}
|
|
144
135
|
/**
|
|
145
136
|
* Parse the protocol from a module name.
|
|
146
137
|
* @param moduleName The module name to parse.
|
|
@@ -223,9 +214,15 @@ export function getExtensionsCacheDir(executionDirectory, protocol, cacheDirecto
|
|
|
223
214
|
*/
|
|
224
215
|
export async function handleNpmProtocol(packageName, executionDirectory, cacheDirectory) {
|
|
225
216
|
const cacheDir = getExtensionsCacheDir(executionDirectory, ModuleProtocol.Npm, cacheDirectory);
|
|
226
|
-
//
|
|
227
|
-
//
|
|
228
|
-
//
|
|
217
|
+
// Strip the version suffix to get the bare package name. We use lastIndexOf
|
|
218
|
+
// (not indexOf) so the leading "@" of a scoped package is preserved - for
|
|
219
|
+
// "@scope/pkg@1.0.0" the last "@" is the version separator at the end, not
|
|
220
|
+
// the scope prefix at position 0. The `> 0` (not `>= 0`) check then leaves
|
|
221
|
+
// unversioned scoped names like "@scope/pkg" untouched, since their only "@"
|
|
222
|
+
// sits at index 0.
|
|
223
|
+
// e.g. "picocolors@1.0.0" → "picocolors"
|
|
224
|
+
// e.g. "@scope/pkg@1.0.0" → "@scope/pkg"
|
|
225
|
+
// e.g. "@scope/pkg" → "@scope/pkg" (unchanged)
|
|
229
226
|
const lastAtIndex = packageName.lastIndexOf("@");
|
|
230
227
|
const packageNameOnly = lastAtIndex > 0 ? packageName.slice(0, lastAtIndex) : packageName;
|
|
231
228
|
const packageDir = path.join(cacheDir, "node_modules", packageNameOnly);
|
|
@@ -244,7 +241,7 @@ export async function handleNpmProtocol(packageName, executionDirectory, cacheDi
|
|
|
244
241
|
try {
|
|
245
242
|
// Always pipe stdio to comply with env access restrictions in tests/lint
|
|
246
243
|
const stdio = "pipe";
|
|
247
|
-
execSync(`npm install ${packageName} --prefix "${cacheDir}" --no-save --no-package-lock`, {
|
|
244
|
+
execSync(`npm install ${packageName} --prefix "${cacheDir}" --omit=dev --no-save --no-package-lock`, {
|
|
248
245
|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C;YAC/D,MAAM,kBAAkB,GAAG,MAAM,YAAY,CAK1C,eAAe,CAAC,CAAC;YAEpB,kDAAkD;YAClD,OAAO,kBAAkB,CAAC,MAAM,IAAI,kBAAkB,CAAC,IAAI,IAAI,QAAQ,CAAC;QACzE,CAAC;QAAC,MAAM,CAAC;YACR,OAAO,QAAQ,CAAC;QACjB,CAAC;IACF,CAAC;AACF,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,qBAAqB,CAAC,QAAgB;IACrD,OAAO,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,UAAU,QAAQ,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC;AACvE,CAAC","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport { execSync } from \"node:child_process\";\nimport { mkdir, readdir, readFile, rename, stat, writeFile } from \"node:fs/promises\";\nimport { get as httpsGet } from \"node:https\";\nimport path from \"node:path\";\nimport { CLIDisplay } from \"@twin.org/cli-core\";\nimport {\n\tBaseError,\n\tConverter,\n\tGeneralError,\n\tI18n,\n\tIs,\n\ttype ILocaleDictionary\n} from \"@twin.org/core\";\nimport { Sha256 } from \"@twin.org/crypto\";\nimport { ModuleHelper } from \"@twin.org/modules\";\nimport type { ICacheMetadata } from \"./models/ICacheMetadata.js\";\nimport type { IModuleProtocol } from \"./models/IModuleProtocol.js\";\nimport type { INodeEnvironmentVariables } from \"./models/INodeEnvironmentVariables.js\";\nimport type { IProtocolHandlerResult } from \"./models/IProtocolHandlerResult.js\";\nimport { ModuleProtocol } from \"./models/moduleProtocol.js\";\nimport { NodeFeatures } from \"./models/nodeFeatures.js\";\n\n/**\n * Initialise the locales for the application.\n * @param localesDirectory The directory containing the locales.\n */\nexport async function initialiseLocales(localesDirectory: string): Promise<void> {\n\tconst localesFile = path.resolve(path.join(localesDirectory, \"en.json\"));\n\tCLIDisplay.value(\"Locales File\", localesFile);\n\tif (await fileExists(localesFile)) {\n\t\tconst enLangContent = await readFile(localesFile, \"utf8\");\n\t\tI18n.addDictionary(\"en\", JSON.parse(enLangContent) as ILocaleDictionary);\n\t} else {\n\t\tCLIDisplay.error(`Locales file not found: ${localesFile}`);\n\t}\n}\n\n/**\n * Get the directory where the application is being executed.\n * @returns The execution directory.\n */\nexport function getExecutionDirectory(): string {\n\treturn process.cwd();\n}\n\n/**\n * Does the specified file exist.\n * @param filename The filename to check for existence.\n * @returns True if the file exists.\n */\nexport async function fileExists(filename: string): Promise<boolean> {\n\ttry {\n\t\tconst stats = await stat(filename);\n\t\treturn stats.isFile();\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Does the specified directory exist.\n * @param directory The directory to check for existence.\n * @returns True if the directory exists.\n */\nexport async function directoryExists(directory: string): Promise<boolean> {\n\ttry {\n\t\tconst stats = await stat(directory);\n\t\treturn stats.isDirectory();\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Get the sub folders for the folder.\n * @param directory The directory to get the sub folders.\n * @returns The list of sub folders.\n */\nexport async function getSubFolders(directory: string): Promise<string[]> {\n\ttry {\n\t\tconst dir = await readdir(directory);\n\t\tconst folders: string[] = [];\n\t\tfor (const dirEntry of dir) {\n\t\t\tconst fullPath = path.join(directory, dirEntry);\n\t\t\tconst stats = await stat(fullPath);\n\t\t\tif (stats.isDirectory()) {\n\t\t\t\tfolders.push(fullPath);\n\t\t\t}\n\t\t}\n\t\treturn folders;\n\t} catch {\n\t\treturn [];\n\t}\n}\n\n/**\n * Get the files in the directory.\n * @param directory The directory to get the files from.\n * @returns The list of files in the directory.\n */\nexport async function getFiles(directory: string): Promise<string[]> {\n\ttry {\n\t\tconst dir = await readdir(directory);\n\t\tconst files: string[] = [];\n\t\tfor (const dirEntry of dir) {\n\t\t\tconst fullPath = path.join(directory, dirEntry);\n\t\t\tconst stats = await stat(fullPath);\n\t\t\tif (stats.isFile()) {\n\t\t\t\tfiles.push(fullPath);\n\t\t\t}\n\t\t}\n\t\treturn files;\n\t} catch {\n\t\treturn [];\n\t}\n}\n\n/**\n * Load the text file.\n * @param filename The filename of the text file to load.\n * @returns The contents of the text file if it could not be loaded.\n */\nexport async function loadTextFile(filename: string): Promise<string> {\n\treturn readFile(filename, \"utf8\");\n}\n\n/**\n * Load the JSON file.\n * @param filename The filename of the JSON file to load.\n * @returns The contents of the JSON file or null if it could not be loaded.\n */\nexport async function loadJsonFile<T>(filename: string): Promise<T> {\n\tconst content = await loadTextFile(filename);\n\treturn JSON.parse(content) as T;\n}\n\n/**\n * Get the features that are enabled on the node.\n * @param env The environment variables for the node.\n * @returns The features that are enabled on the node.\n */\nexport function getFeatures(env: INodeEnvironmentVariables): NodeFeatures[] {\n\tif (Is.empty(env.features)) {\n\t\treturn [];\n\t}\n\n\tconst features: NodeFeatures[] = [];\n\tconst allFeatures = Object.values(NodeFeatures);\n\n\tconst splitFeatures = env.features.split(\",\");\n\tfor (const feature of splitFeatures) {\n\t\tconst featureTrimmed = feature.trim() as NodeFeatures;\n\t\tif (allFeatures.includes(featureTrimmed)) {\n\t\t\tfeatures.push(featureTrimmed);\n\t\t}\n\t}\n\n\treturn features;\n}\n\n/**\n * Parse the protocol from a module name.\n * @param moduleName The module name to parse.\n * @returns The parsed protocol information.\n */\nexport function parseModuleProtocol(moduleName: string): IModuleProtocol {\n\tconst trimmed = moduleName.trim();\n\n\tif (trimmed.startsWith(\"npm:\")) {\n\t\treturn {\n\t\t\tprotocol: ModuleProtocol.Npm,\n\t\t\tidentifier: trimmed.slice(4),\n\t\t\toriginal: trimmed\n\t\t};\n\t}\n\n\tif (trimmed.startsWith(\"https://\")) {\n\t\treturn {\n\t\t\tprotocol: ModuleProtocol.Https,\n\t\t\tidentifier: trimmed,\n\t\t\toriginal: trimmed\n\t\t};\n\t}\n\n\tif (trimmed.startsWith(\"http://\")) {\n\t\treturn {\n\t\t\tprotocol: ModuleProtocol.Http,\n\t\t\tidentifier: trimmed,\n\t\t\toriginal: trimmed\n\t\t};\n\t}\n\n\tif (trimmed.startsWith(\"file://\")) {\n\t\treturn {\n\t\t\tprotocol: ModuleProtocol.Local,\n\t\t\tidentifier: trimmed,\n\t\t\toriginal: trimmed\n\t\t};\n\t}\n\n\tif (ModuleHelper.isLocalModule(trimmed)) {\n\t\treturn {\n\t\t\tprotocol: ModuleProtocol.Local,\n\t\t\tidentifier: trimmed,\n\t\t\toriginal: trimmed\n\t\t};\n\t}\n\n\treturn {\n\t\tprotocol: ModuleProtocol.Default,\n\t\tidentifier: trimmed,\n\t\toriginal: trimmed\n\t};\n}\n\n/**\n * Hash a URL to create a safe filename.\n * @param url The URL to hash.\n * @returns A hashed filename safe for the filesystem.\n */\nexport function hashUrl(url: string): string {\n\tconst urlBytes = Converter.utf8ToBytes(url);\n\tconst hashBytes = Sha256.sum256(urlBytes);\n\tconst hash = Converter.bytesToHex(hashBytes);\n\tconst ext = path.extname(new URL(url).pathname);\n\treturn `${hash}${ext}`;\n}\n\n/**\n * Get the extensions cache directory.\n * @param executionDirectory The execution directory.\n * @param protocol The protocol type for subdirectory organization.\n * @param cacheDirectory The cache directory base path.\n * @returns The cache directory path.\n */\nexport function getExtensionsCacheDir(\n\texecutionDirectory: string,\n\tprotocol: ModuleProtocol,\n\tcacheDirectory?: string\n): string {\n\t// Resolve to absolute path to ensure consistent behavior\n\tconst absoluteDir = path.resolve(executionDirectory);\n\tconst baseDir = cacheDirectory ?? \".tmp\";\n\treturn path.join(absoluteDir, baseDir, \"extensions\", protocol);\n}\n\n/**\n * Handle the npm: protocol by installing the package if needed.\n * @param packageName The npm package name (without npm: prefix).\n * @param executionDirectory The execution directory.\n * @param cacheDirectory The cache directory base path.\n * @returns The resolved path to the installed module.\n */\nexport async function handleNpmProtocol(\n\tpackageName: string,\n\texecutionDirectory: string,\n\tcacheDirectory?: string\n): Promise<IProtocolHandlerResult> {\n\tconst cacheDir = getExtensionsCacheDir(executionDirectory, ModuleProtocol.Npm, cacheDirectory);\n\t// Extract just the package name (without version) for the directory\n\t// e.g. \"picocolors@1.0.0\" becomes \"picocolors\"\n\t// e.g. \"@scope/package@1.0.0\" becomes \"@scope/package\"\n\tconst lastAtIndex = packageName.lastIndexOf(\"@\");\n\tconst packageNameOnly = lastAtIndex > 0 ? packageName.slice(0, lastAtIndex) : packageName;\n\tconst packageDir = path.join(cacheDir, \"node_modules\", packageNameOnly);\n\tconst packageJsonPath = path.join(packageDir, \"package.json\");\n\n\tconst exists = await fileExists(packageJsonPath);\n\tif (exists) {\n\t\tconst mainFile = await resolvePackageEntryPoint(packageDir, packageNameOnly);\n\t\tconst modulePath = path.join(packageDir, mainFile);\n\n\t\treturn {\n\t\t\tresolvedPath: modulePath,\n\t\t\tcached: true\n\t\t};\n\t}\n\n\tawait mkdir(cacheDir, { recursive: true });\n\n\tCLIDisplay.task(I18n.formatMessage(\"node.extensionNpmInstalling\"), packageName);\n\n\ttry {\n\t\t// Always pipe stdio to comply with env access restrictions in tests/lint\n\t\tconst stdio: \"pipe\" | \"inherit\" | \"ignore\" = \"pipe\";\n\t\texecSync(`npm install ${packageName} --prefix \"${cacheDir}\" --no-save --no-package-lock`, {\n\t\t\tcwd: cacheDir,\n\t\t\tstdio\n\t\t});\n\t} catch (err) {\n\t\tthrow new GeneralError(\n\t\t\t\"node\",\n\t\t\t\"extensionNpmInstallFailed\",\n\t\t\t{\n\t\t\t\tpackage: packageName\n\t\t\t},\n\t\t\tBaseError.fromError(err)\n\t\t);\n\t}\n\n\tconst mainFile = await resolvePackageEntryPoint(packageDir, packageNameOnly);\n\tconst modulePath = path.join(packageDir, mainFile);\n\n\treturn {\n\t\tresolvedPath: modulePath,\n\t\tcached: false\n\t};\n}\n\n/**\n * Check if a cached file has expired based on TTL and force refresh settings.\n * @param metadataPath Path to the cache metadata file.\n * @param ttlHours Time to live in hours.\n * @param forceRefresh Whether to force refresh regardless of TTL.\n * @returns True if the cache is expired or should be refreshed.\n */\nexport async function isCacheExpired(\n\tmetadataPath: string,\n\tttlHours: number,\n\tforceRefresh: boolean\n): Promise<boolean> {\n\tif (forceRefresh) {\n\t\treturn true;\n\t}\n\n\ttry {\n\t\tconst metadata = await loadJsonFile<ICacheMetadata>(metadataPath);\n\t\tconst ttlMillis = ttlHours * 60 * 60 * 1000;\n\t\tconst expireTime = metadata.downloadedAt + ttlMillis;\n\t\treturn Date.now() > expireTime;\n\t} catch {\n\t\t// If metadata doesn't exist or is corrupted, consider expired\n\t\treturn true;\n\t}\n}\n\n/**\n * Handle the https: protocol by downloading the module if needed.\n * @param url The HTTPS URL to download from.\n * @param executionDirectory The execution directory.\n * @param maxSizeMb The maximum size in MB for the download.\n * @param cacheDirectory The cache directory base path.\n * @param ttlHours TTL in hours for cache expiration.\n * @param forceRefresh Whether to force refresh the cache.\n * @returns The resolved path to the downloaded module.\n */\nexport async function handleHttpsProtocol(\n\turl: string,\n\texecutionDirectory: string,\n\tmaxSizeMb: number,\n\tcacheDirectory?: string,\n\tttlHours?: number,\n\tforceRefresh?: boolean\n): Promise<IProtocolHandlerResult> {\n\tconst effectiveTtlHours = ttlHours ?? 24;\n\tconst effectiveForceRefresh = forceRefresh ?? false;\n\tconst cacheDir = getExtensionsCacheDir(executionDirectory, ModuleProtocol.Https, cacheDirectory);\n\tconst filename = hashUrl(url);\n\tconst cachedPath = path.join(cacheDir, filename);\n\tconst metadataPath = `${cachedPath}.meta`;\n\n\tconst exists = await fileExists(cachedPath);\n\tif (exists) {\n\t\tconst expired = await isCacheExpired(metadataPath, effectiveTtlHours, effectiveForceRefresh);\n\t\tif (!expired) {\n\t\t\treturn {\n\t\t\t\tresolvedPath: cachedPath,\n\t\t\t\tcached: true\n\t\t\t};\n\t\t}\n\n\t\tif (effectiveForceRefresh) {\n\t\t\tCLIDisplay.warning(I18n.formatMessage(\"node.extensionForceRefresh\", { url }));\n\t\t} else {\n\t\t\tCLIDisplay.task(I18n.formatMessage(\"node.extensionCacheExpired\", { url }));\n\t\t}\n\t}\n\n\tCLIDisplay.warning(I18n.formatMessage(\"node.extensionSecurityWarning\", { url }));\n\tCLIDisplay.task(I18n.formatMessage(\"node.extensionHttpsDownloading\"), url);\n\n\tawait mkdir(cacheDir, { recursive: true });\n\n\tconst maxSizeBytes = maxSizeMb * 1024 * 1024;\n\tlet downloadedSize = 0;\n\tconst chunks: Buffer[] = [];\n\n\ttry {\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\thttpsGet(url, response => {\n\t\t\t\tif (response.statusCode !== 200) {\n\t\t\t\t\treject(\n\t\t\t\t\t\tnew GeneralError(\"node\", \"extensionDownloadFailed\", {\n\t\t\t\t\t\t\turl,\n\t\t\t\t\t\t\tstatus: response.statusCode ?? 0\n\t\t\t\t\t\t})\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tresponse.on(\"data\", (chunk: Buffer) => {\n\t\t\t\t\tdownloadedSize += chunk.length;\n\n\t\t\t\t\tif (downloadedSize > maxSizeBytes) {\n\t\t\t\t\t\tresponse.destroy();\n\t\t\t\t\t\treject(\n\t\t\t\t\t\t\tnew GeneralError(\"node\", \"extensionSizeLimitExceeded\", {\n\t\t\t\t\t\t\t\tsize: downloadedSize,\n\t\t\t\t\t\t\t\tlimit: maxSizeBytes\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tchunks.push(chunk);\n\t\t\t\t});\n\n\t\t\t\tresponse.on(\"end\", () => {\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\n\t\t\t\tresponse.on(\"error\", err => {\n\t\t\t\t\treject(BaseError.fromError(err));\n\t\t\t\t});\n\t\t\t}).on(\"error\", err => {\n\t\t\t\treject(BaseError.fromError(err));\n\t\t\t});\n\t\t});\n\t} catch (err) {\n\t\tthrow new GeneralError(\n\t\t\t\"node\",\n\t\t\t\"extensionDownloadFailed\",\n\t\t\t{\n\t\t\t\turl\n\t\t\t},\n\t\t\tBaseError.fromError(err)\n\t\t);\n\t}\n\n\tconst tempPath = `${cachedPath}.tmp`;\n\tawait writeFile(tempPath, Buffer.concat(chunks));\n\n\t// Atomic move from temp to final location\n\tawait rename(tempPath, cachedPath);\n\n\t// Save metadata for TTL tracking\n\tconst metadata: ICacheMetadata = {\n\t\tdownloadedAt: Date.now(),\n\t\turl,\n\t\tsize: Buffer.concat(chunks).length\n\t};\n\tawait writeFile(metadataPath, JSON.stringify(metadata, null, 2));\n\n\treturn {\n\t\tresolvedPath: cachedPath,\n\t\tcached: false\n\t};\n}\n\n/**\n * Resolve the main entry point from a package directory using Node.js resolution with fallback.\n * Uses require.resolve() when possible for standard Node.js behavior, with manual fallback.\n * @param packagePath The absolute path to the package directory.\n * @param packageName The package name for require.resolve().\n * @param fallback The fallback file name if no entry point is found.\n * @returns The resolved entry point file name (relative to package directory).\n */\nexport async function resolvePackageEntryPoint(\n\tpackagePath: string,\n\tpackageName: string,\n\tfallback = \"index.js\"\n): Promise<string> {\n\ttry {\n\t\t// Try require.resolve() first - handles exports, main, module automatically\n\t\tconst resolvedPath = require.resolve(packageName, { paths: [path.dirname(packagePath)] });\n\t\t// Convert absolute path back to relative filename within package\n\t\tconst relativePath = path.relative(packagePath, resolvedPath);\n\t\treturn relativePath ?? fallback;\n\t} catch {\n\t\t// Fallback to manual package.json parsing if require.resolve fails\n\t\ttry {\n\t\t\tconst packageJsonPath = path.join(packagePath, \"package.json\");\n\t\t\tconst packageJsonContent = await loadJsonFile<{\n\t\t\t\tmodule?: string;\n\t\t\t\tmain?: string;\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\t\t\t\texports?: any;\n\t\t\t}>(packageJsonPath);\n\n\t\t\t// Future: Could expand exports field support here\n\t\t\treturn packageJsonContent.module ?? packageJsonContent.main ?? fallback;\n\t\t} catch {\n\t\t\treturn fallback;\n\t\t}\n\t}\n}\n\n/**\n * Convert a file path to an import-compatible URL for cross-platform module loading.\n * On Windows, adds the 'file://' protocol prefix required for dynamic imports.\n * On other platforms, returns the path unchanged.\n * @param filePath The absolute file path to convert.\n * @returns A URL string compatible with dynamic import().\n */\nexport function createModuleImportUrl(filePath: string): string {\n\treturn process.platform === \"win32\" ? `file://${filePath}` : filePath;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AACvC,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACrF,OAAO,EAAE,GAAG,IAAI,QAAQ,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EACN,SAAS,EACT,SAAS,EACT,YAAY,EACZ,IAAI,EACJ,EAAE,EAEF,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAIjD,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAE5D;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CAAC,gBAAwB;IAC/D,MAAM,WAAW,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,SAAS,CAAC,CAAC,CAAC;IACzE,UAAU,CAAC,KAAK,CAAC,cAAc,EAAE,WAAW,CAAC,CAAC;IAC9C,IAAI,MAAM,UAAU,CAAC,WAAW,CAAC,EAAE,CAAC;QACnC,MAAM,aAAa,GAAG,MAAM,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;QAC1D,IAAI,CAAC,aAAa,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,aAAa,CAAsB,CAAC,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,IAAI,QAAQ,CAAC;QACzE,CAAC;QAAC,MAAM,CAAC;YACR,OAAO,QAAQ,CAAC;QACjB,CAAC;IACF,CAAC;AACF,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,qBAAqB,CAAC,QAAgB;IACrD,OAAO,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,UAAU,QAAQ,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC;AACvE,CAAC","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport { execSync } from \"node:child_process\";\nimport { mkdir, readdir, readFile, rename, stat, writeFile } from \"node:fs/promises\";\nimport { get as httpsGet } from \"node:https\";\nimport path from \"node:path\";\nimport { CLIDisplay } from \"@twin.org/cli-core\";\nimport {\n\tBaseError,\n\tConverter,\n\tGeneralError,\n\tI18n,\n\tIs,\n\ttype ILocaleDictionary\n} from \"@twin.org/core\";\nimport { Sha256 } from \"@twin.org/crypto\";\nimport { ModuleHelper } from \"@twin.org/modules\";\nimport type { ICacheMetadata } from \"./models/ICacheMetadata.js\";\nimport type { IModuleProtocol } from \"./models/IModuleProtocol.js\";\nimport type { IProtocolHandlerResult } from \"./models/IProtocolHandlerResult.js\";\nimport { ModuleProtocol } from \"./models/moduleProtocol.js\";\n\n/**\n * Initialise the locales for the application.\n * @param localesDirectory The directory containing the locales.\n * @returns A promise that resolves when the locale dictionary has been loaded.\n */\nexport async function initialiseLocales(localesDirectory: string): Promise<void> {\n\tconst localesFile = path.resolve(path.join(localesDirectory, \"en.json\"));\n\tCLIDisplay.value(\"Locales File\", localesFile);\n\tif (await fileExists(localesFile)) {\n\t\tconst enLangContent = await readFile(localesFile, \"utf8\");\n\t\tI18n.addDictionary(\"en\", JSON.parse(enLangContent) as ILocaleDictionary);\n\t} else {\n\t\tCLIDisplay.error(`Locales file not found: ${localesFile}`);\n\t}\n}\n\n/**\n * Get the directory where the application is being executed.\n * @returns The execution directory.\n */\nexport function getExecutionDirectory(): string {\n\treturn process.cwd();\n}\n\n/**\n * Get the directory where the script is located.\n * @param args The command line arguments.\n * @returns The directory containing the entry-point script, or the current working directory if not determinable.\n */\nexport function getScriptDirectory(args?: string[]): string {\n\tif (Is.array<string>(args) && args.length >= 2 && args[1].includes(\"index.js\")) {\n\t\treturn path.resolve(path.join(path.dirname(args[1]), \"..\"));\n\t}\n\treturn process.cwd();\n}\n\n/**\n * Does the specified file exist.\n * @param filename The filename to check for existence.\n * @returns True if the file exists.\n */\nexport async function fileExists(filename: string): Promise<boolean> {\n\ttry {\n\t\tconst stats = await stat(filename);\n\t\treturn stats.isFile();\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Does the specified directory exist.\n * @param directory The directory to check for existence.\n * @returns True if the directory exists.\n */\nexport async function directoryExists(directory: string): Promise<boolean> {\n\ttry {\n\t\tconst stats = await stat(directory);\n\t\treturn stats.isDirectory();\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Get the sub folders for the folder.\n * @param directory The directory to get the sub folders.\n * @returns The list of sub folders.\n */\nexport async function getSubFolders(directory: string): Promise<string[]> {\n\ttry {\n\t\tconst dir = await readdir(directory);\n\t\tconst folders: string[] = [];\n\t\tfor (const dirEntry of dir) {\n\t\t\tconst fullPath = path.join(directory, dirEntry);\n\t\t\tconst stats = await stat(fullPath);\n\t\t\tif (stats.isDirectory()) {\n\t\t\t\tfolders.push(fullPath);\n\t\t\t}\n\t\t}\n\t\treturn folders;\n\t} catch {\n\t\treturn [];\n\t}\n}\n\n/**\n * Get the files in the directory.\n * @param directory The directory to get the files from.\n * @returns The list of files in the directory.\n */\nexport async function getFiles(directory: string): Promise<string[]> {\n\ttry {\n\t\tconst dir = await readdir(directory);\n\t\tconst files: string[] = [];\n\t\tfor (const dirEntry of dir) {\n\t\t\tconst fullPath = path.join(directory, dirEntry);\n\t\t\tconst stats = await stat(fullPath);\n\t\t\tif (stats.isFile()) {\n\t\t\t\tfiles.push(fullPath);\n\t\t\t}\n\t\t}\n\t\treturn files;\n\t} catch {\n\t\treturn [];\n\t}\n}\n\n/**\n * Load the text file.\n * @param filename The filename of the text file to load.\n * @returns The contents of the text file as a UTF-8 string.\n */\nexport async function loadTextFile(filename: string): Promise<string> {\n\treturn readFile(filename, \"utf8\");\n}\n\n/**\n * Load the JSON file.\n * @param filename The filename of the JSON file to load.\n * @returns The parsed JSON content of the file.\n */\nexport async function loadJsonFile<T>(filename: string): Promise<T> {\n\tconst content = await loadTextFile(filename);\n\treturn JSON.parse(content) as T;\n}\n\n/**\n * Parse the protocol from a module name.\n * @param moduleName The module name to parse.\n * @returns The parsed protocol information.\n */\nexport function parseModuleProtocol(moduleName: string): IModuleProtocol {\n\tconst trimmed = moduleName.trim();\n\n\tif (trimmed.startsWith(\"npm:\")) {\n\t\treturn {\n\t\t\tprotocol: ModuleProtocol.Npm,\n\t\t\tidentifier: trimmed.slice(4),\n\t\t\toriginal: trimmed\n\t\t};\n\t}\n\n\tif (trimmed.startsWith(\"https://\")) {\n\t\treturn {\n\t\t\tprotocol: ModuleProtocol.Https,\n\t\t\tidentifier: trimmed,\n\t\t\toriginal: trimmed\n\t\t};\n\t}\n\n\tif (trimmed.startsWith(\"http://\")) {\n\t\treturn {\n\t\t\tprotocol: ModuleProtocol.Http,\n\t\t\tidentifier: trimmed,\n\t\t\toriginal: trimmed\n\t\t};\n\t}\n\n\tif (trimmed.startsWith(\"file://\")) {\n\t\treturn {\n\t\t\tprotocol: ModuleProtocol.Local,\n\t\t\tidentifier: trimmed,\n\t\t\toriginal: trimmed\n\t\t};\n\t}\n\n\tif (ModuleHelper.isLocalModule(trimmed)) {\n\t\treturn {\n\t\t\tprotocol: ModuleProtocol.Local,\n\t\t\tidentifier: trimmed,\n\t\t\toriginal: trimmed\n\t\t};\n\t}\n\n\treturn {\n\t\tprotocol: ModuleProtocol.Default,\n\t\tidentifier: trimmed,\n\t\toriginal: trimmed\n\t};\n}\n\n/**\n * Hash a URL to create a safe filename.\n * @param url The URL to hash.\n * @returns A hashed filename safe for the filesystem.\n */\nexport function hashUrl(url: string): string {\n\tconst urlBytes = Converter.utf8ToBytes(url);\n\tconst hashBytes = Sha256.sum256(urlBytes);\n\tconst hash = Converter.bytesToHex(hashBytes);\n\tconst ext = path.extname(new URL(url).pathname);\n\treturn `${hash}${ext}`;\n}\n\n/**\n * Get the extensions cache directory.\n * @param executionDirectory The execution directory.\n * @param protocol The protocol type for subdirectory organization.\n * @param cacheDirectory The cache directory base path.\n * @returns The cache directory path.\n */\nexport function getExtensionsCacheDir(\n\texecutionDirectory: string,\n\tprotocol: ModuleProtocol,\n\tcacheDirectory?: string\n): string {\n\t// Resolve to absolute path to ensure consistent behavior\n\tconst absoluteDir = path.resolve(executionDirectory);\n\tconst baseDir = cacheDirectory ?? \".tmp\";\n\treturn path.join(absoluteDir, baseDir, \"extensions\", protocol);\n}\n\n/**\n * Handle the npm: protocol by installing the package if needed.\n * @param packageName The npm package name (without npm: prefix).\n * @param executionDirectory The execution directory.\n * @param cacheDirectory The cache directory base path.\n * @returns The resolved path to the installed module.\n */\nexport async function handleNpmProtocol(\n\tpackageName: string,\n\texecutionDirectory: string,\n\tcacheDirectory?: string\n): Promise<IProtocolHandlerResult> {\n\tconst cacheDir = getExtensionsCacheDir(executionDirectory, ModuleProtocol.Npm, cacheDirectory);\n\t// Strip the version suffix to get the bare package name. We use lastIndexOf\n\t// (not indexOf) so the leading \"@\" of a scoped package is preserved - for\n\t// \"@scope/pkg@1.0.0\" the last \"@\" is the version separator at the end, not\n\t// the scope prefix at position 0. The `> 0` (not `>= 0`) check then leaves\n\t// unversioned scoped names like \"@scope/pkg\" untouched, since their only \"@\"\n\t// sits at index 0.\n\t// e.g. \"picocolors@1.0.0\" → \"picocolors\"\n\t// e.g. \"@scope/pkg@1.0.0\" → \"@scope/pkg\"\n\t// e.g. \"@scope/pkg\" → \"@scope/pkg\" (unchanged)\n\tconst lastAtIndex = packageName.lastIndexOf(\"@\");\n\tconst packageNameOnly = lastAtIndex > 0 ? packageName.slice(0, lastAtIndex) : packageName;\n\tconst packageDir = path.join(cacheDir, \"node_modules\", packageNameOnly);\n\tconst packageJsonPath = path.join(packageDir, \"package.json\");\n\n\tconst exists = await fileExists(packageJsonPath);\n\tif (exists) {\n\t\tconst mainFile = await resolvePackageEntryPoint(packageDir, packageNameOnly);\n\t\tconst modulePath = path.join(packageDir, mainFile);\n\n\t\treturn {\n\t\t\tresolvedPath: modulePath,\n\t\t\tcached: true\n\t\t};\n\t}\n\n\tawait mkdir(cacheDir, { recursive: true });\n\n\tCLIDisplay.task(I18n.formatMessage(\"node.extensionNpmInstalling\"), packageName);\n\n\ttry {\n\t\t// Always pipe stdio to comply with env access restrictions in tests/lint\n\t\tconst stdio: \"pipe\" | \"inherit\" | \"ignore\" = \"pipe\";\n\t\texecSync(\n\t\t\t`npm install ${packageName} --prefix \"${cacheDir}\" --omit=dev --no-save --no-package-lock`,\n\t\t\t{\n\t\t\t\tcwd: cacheDir,\n\t\t\t\tstdio\n\t\t\t}\n\t\t);\n\t} catch (err) {\n\t\tthrow new GeneralError(\n\t\t\t\"node\",\n\t\t\t\"extensionNpmInstallFailed\",\n\t\t\t{\n\t\t\t\tpackage: packageName\n\t\t\t},\n\t\t\tBaseError.fromError(err)\n\t\t);\n\t}\n\n\tconst mainFile = await resolvePackageEntryPoint(packageDir, packageNameOnly);\n\tconst modulePath = path.join(packageDir, mainFile);\n\n\treturn {\n\t\tresolvedPath: modulePath,\n\t\tcached: false\n\t};\n}\n\n/**\n * Check if a cached file has expired based on TTL and force refresh settings.\n * @param metadataPath Path to the cache metadata file.\n * @param ttlHours Time to live in hours.\n * @param forceRefresh Whether to force refresh regardless of TTL.\n * @returns True if the cache is expired or should be refreshed.\n */\nexport async function isCacheExpired(\n\tmetadataPath: string,\n\tttlHours: number,\n\tforceRefresh: boolean\n): Promise<boolean> {\n\tif (forceRefresh) {\n\t\treturn true;\n\t}\n\n\ttry {\n\t\tconst metadata = await loadJsonFile<ICacheMetadata>(metadataPath);\n\t\tconst ttlMillis = ttlHours * 60 * 60 * 1000;\n\t\tconst expireTime = metadata.downloadedAt + ttlMillis;\n\t\treturn Date.now() > expireTime;\n\t} catch {\n\t\t// If metadata doesn't exist or is corrupted, consider expired\n\t\treturn true;\n\t}\n}\n\n/**\n * Handle the https: protocol by downloading the module if needed.\n * @param url The HTTPS URL to download from.\n * @param executionDirectory The execution directory.\n * @param maxSizeMb The maximum size in MB for the download.\n * @param cacheDirectory The cache directory base path.\n * @param ttlHours TTL in hours for cache expiration.\n * @param forceRefresh Whether to force refresh the cache.\n * @returns The resolved path to the downloaded module.\n */\nexport async function handleHttpsProtocol(\n\turl: string,\n\texecutionDirectory: string,\n\tmaxSizeMb: number,\n\tcacheDirectory?: string,\n\tttlHours?: number,\n\tforceRefresh?: boolean\n): Promise<IProtocolHandlerResult> {\n\tconst effectiveTtlHours = ttlHours ?? 24;\n\tconst effectiveForceRefresh = forceRefresh ?? false;\n\tconst cacheDir = getExtensionsCacheDir(executionDirectory, ModuleProtocol.Https, cacheDirectory);\n\tconst filename = hashUrl(url);\n\tconst cachedPath = path.join(cacheDir, filename);\n\tconst metadataPath = `${cachedPath}.meta`;\n\n\tconst exists = await fileExists(cachedPath);\n\tif (exists) {\n\t\tconst expired = await isCacheExpired(metadataPath, effectiveTtlHours, effectiveForceRefresh);\n\t\tif (!expired) {\n\t\t\treturn {\n\t\t\t\tresolvedPath: cachedPath,\n\t\t\t\tcached: true\n\t\t\t};\n\t\t}\n\n\t\tif (effectiveForceRefresh) {\n\t\t\tCLIDisplay.warning(I18n.formatMessage(\"node.extensionForceRefresh\", { url }));\n\t\t} else {\n\t\t\tCLIDisplay.task(I18n.formatMessage(\"node.extensionCacheExpired\", { url }));\n\t\t}\n\t}\n\n\tCLIDisplay.warning(I18n.formatMessage(\"node.extensionSecurityWarning\", { url }));\n\tCLIDisplay.task(I18n.formatMessage(\"node.extensionHttpsDownloading\"), url);\n\n\tawait mkdir(cacheDir, { recursive: true });\n\n\tconst maxSizeBytes = maxSizeMb * 1024 * 1024;\n\tlet downloadedSize = 0;\n\tconst chunks: Buffer[] = [];\n\n\ttry {\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\thttpsGet(url, response => {\n\t\t\t\tif (response.statusCode !== 200) {\n\t\t\t\t\treject(\n\t\t\t\t\t\tnew GeneralError(\"node\", \"extensionDownloadFailed\", {\n\t\t\t\t\t\t\turl,\n\t\t\t\t\t\t\tstatus: response.statusCode ?? 0\n\t\t\t\t\t\t})\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tresponse.on(\"data\", (chunk: Buffer) => {\n\t\t\t\t\tdownloadedSize += chunk.length;\n\n\t\t\t\t\tif (downloadedSize > maxSizeBytes) {\n\t\t\t\t\t\tresponse.destroy();\n\t\t\t\t\t\treject(\n\t\t\t\t\t\t\tnew GeneralError(\"node\", \"extensionSizeLimitExceeded\", {\n\t\t\t\t\t\t\t\tsize: downloadedSize,\n\t\t\t\t\t\t\t\tlimit: maxSizeBytes\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tchunks.push(chunk);\n\t\t\t\t});\n\n\t\t\t\tresponse.on(\"end\", () => {\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\n\t\t\t\tresponse.on(\"error\", err => {\n\t\t\t\t\treject(BaseError.fromError(err));\n\t\t\t\t});\n\t\t\t}).on(\"error\", err => {\n\t\t\t\treject(BaseError.fromError(err));\n\t\t\t});\n\t\t});\n\t} catch (err) {\n\t\tthrow new GeneralError(\n\t\t\t\"node\",\n\t\t\t\"extensionDownloadFailed\",\n\t\t\t{\n\t\t\t\turl\n\t\t\t},\n\t\t\tBaseError.fromError(err)\n\t\t);\n\t}\n\n\tconst tempPath = `${cachedPath}.tmp`;\n\tawait writeFile(tempPath, Buffer.concat(chunks));\n\n\t// Atomic move from temp to final location\n\tawait rename(tempPath, cachedPath);\n\n\t// Save metadata for TTL tracking\n\tconst metadata: ICacheMetadata = {\n\t\tdownloadedAt: Date.now(),\n\t\turl,\n\t\tsize: Buffer.concat(chunks).length\n\t};\n\tawait writeFile(metadataPath, JSON.stringify(metadata, null, 2));\n\n\treturn {\n\t\tresolvedPath: cachedPath,\n\t\tcached: false\n\t};\n}\n\n/**\n * Resolve the main entry point from a package directory using Node.js resolution with fallback.\n * Uses require.resolve() when possible for standard Node.js behavior, with manual fallback.\n * @param packagePath The absolute path to the package directory.\n * @param packageName The package name for require.resolve().\n * @param fallback The fallback file name if no entry point is found.\n * @returns The resolved entry point file name (relative to package directory).\n */\nexport async function resolvePackageEntryPoint(\n\tpackagePath: string,\n\tpackageName: string,\n\tfallback = \"index.js\"\n): Promise<string> {\n\ttry {\n\t\t// Try require.resolve() first - handles exports, main, module automatically\n\t\tconst resolvedPath = require.resolve(packageName, { paths: [path.dirname(packagePath)] });\n\t\t// Convert absolute path back to relative filename within package\n\t\tconst relativePath = path.relative(packagePath, resolvedPath);\n\t\treturn relativePath ?? fallback;\n\t} catch {\n\t\t// Fallback to manual package.json parsing if require.resolve fails\n\t\ttry {\n\t\t\tconst packageJsonPath = path.join(packagePath, \"package.json\");\n\t\t\tconst packageJsonContent = await loadJsonFile<{\n\t\t\t\tmodule?: string;\n\t\t\t\tmain?: string;\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\t\t\t\texports?: any;\n\t\t\t}>(packageJsonPath);\n\n\t\t\t// Future: Could expand exports field support here\n\t\t\treturn packageJsonContent.module ?? packageJsonContent.main ?? fallback;\n\t\t} catch {\n\t\t\treturn fallback;\n\t\t}\n\t}\n}\n\n/**\n * Convert a file path to an import-compatible URL for cross-platform module loading.\n * On Windows, adds the 'file://' protocol prefix required for dynamic imports.\n * On other platforms, returns the path unchanged.\n * @param filePath The absolute file path to convert.\n * @returns A URL string compatible with dynamic import().\n */\nexport function createModuleImportUrl(filePath: string): string {\n\treturn process.platform === \"win32\" ? `file://${filePath}` : filePath;\n}\n"]}
|
|
@@ -3,10 +3,65 @@ import type { IEngineEnvironmentVariables } from "../models/IEngineEnvironmentVa
|
|
|
3
3
|
/**
|
|
4
4
|
* Build the engine core configuration from environment variables.
|
|
5
5
|
* @param envVars The environment variables.
|
|
6
|
-
* @param contextIdKeys The context ID keys.
|
|
7
6
|
* @returns The config for the core.
|
|
8
7
|
*/
|
|
9
|
-
export declare function buildEngineConfiguration(envVars: IEngineEnvironmentVariables
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
8
|
+
export declare function buildEngineConfiguration(envVars: IEngineEnvironmentVariables): Promise<IEngineConfig>;
|
|
9
|
+
/**
|
|
10
|
+
* Checks if the trust subsystem is required.
|
|
11
|
+
* Returns true when any component that depends on the trust subsystem is enabled.
|
|
12
|
+
* @param envVars The environment variables.
|
|
13
|
+
* @returns True if rights-management, or dataspace is enabled.
|
|
14
|
+
*/
|
|
15
|
+
export declare function isTrustRequired(envVars: IEngineEnvironmentVariables): boolean;
|
|
16
|
+
/**
|
|
17
|
+
* Checks if the background tasks subsystem is required.
|
|
18
|
+
* Returns true when any component that depends on the background tasks subsystem is enabled.
|
|
19
|
+
* @param envVars The environment variables.
|
|
20
|
+
* @returns True if dataspace or verifiable storage is enabled.
|
|
21
|
+
*/
|
|
22
|
+
export declare function isBackgroundTasksRequired(envVars: IEngineEnvironmentVariables): boolean;
|
|
23
|
+
/**
|
|
24
|
+
* Checks if the immutable proof subsystem is required.
|
|
25
|
+
* Returns true when any component that depends on the immutable proof subsystem is enabled.
|
|
26
|
+
* @param envVars The environment variables.
|
|
27
|
+
* @returns True if verifiable storage is enabled.
|
|
28
|
+
*/
|
|
29
|
+
export declare function isImmutableProofRequired(envVars: IEngineEnvironmentVariables): boolean;
|
|
30
|
+
/**
|
|
31
|
+
* Checks if the federated catalogue subsystem is required.
|
|
32
|
+
* Returns true when the catalogue is explicitly enabled, a remote endpoint is configured, filters are set, or dataspace is enabled.
|
|
33
|
+
* @param envVars The environment variables.
|
|
34
|
+
* @returns True if the federated catalogue is required.
|
|
35
|
+
*/
|
|
36
|
+
export declare function isFederatedCatalogueRequired(envVars: IEngineEnvironmentVariables): boolean;
|
|
37
|
+
/**
|
|
38
|
+
* Checks if the rights management subsystem is required.
|
|
39
|
+
* Returns true when any component that depends on the rights management subsystem is enabled.
|
|
40
|
+
* Note: rights management has no standalone enable flag - it is gated entirely on
|
|
41
|
+
* `dataspaceEnabled`. Setting `TWIN_RIGHTS_MANAGEMENT_*` env var in isolation does not
|
|
42
|
+
* enable the subsystem; `TWIN_DATASPACE_ENABLED` must also be true.
|
|
43
|
+
* @param envVars The environment variables.
|
|
44
|
+
* @returns True if rights management is enabled.
|
|
45
|
+
*/
|
|
46
|
+
export declare function isRightsManagementRequired(envVars: IEngineEnvironmentVariables): boolean;
|
|
47
|
+
/**
|
|
48
|
+
* Checks if the task scheduler subsystem is required.
|
|
49
|
+
* Returns true when any component that depends on the task scheduler subsystem is enabled.
|
|
50
|
+
* @param envVars The environment variables.
|
|
51
|
+
* @returns True if task scheduler is enabled.
|
|
52
|
+
*/
|
|
53
|
+
export declare function isTaskSchedulerRequired(envVars: IEngineEnvironmentVariables): boolean;
|
|
54
|
+
/**
|
|
55
|
+
* Checks if the automation subsystem is required.
|
|
56
|
+
* Returns true when any component that depends on the automation subsystem is enabled.
|
|
57
|
+
* @param envVars The environment variables.
|
|
58
|
+
* @returns True if automation is enabled.
|
|
59
|
+
*/
|
|
60
|
+
export declare function isAutomationRequired(envVars: IEngineEnvironmentVariables): boolean;
|
|
61
|
+
/**
|
|
62
|
+
* Checks if the telemetry subsystem is required.
|
|
63
|
+
* Returns true when any component that depends on the telemetry subsystem is enabled.
|
|
64
|
+
* @param envVars The environment variables.
|
|
65
|
+
* @returns True if telemetry is enabled.
|
|
66
|
+
*/
|
|
67
|
+
export declare function isTelemetryRequired(envVars: IEngineEnvironmentVariables): boolean;
|
|
@@ -12,7 +12,16 @@ import type { IEngineServerEnvironmentVariables } from "../models/IEngineServerE
|
|
|
12
12
|
* @param favIconPath The path to the favicon.
|
|
13
13
|
* @returns The config for the core and the server.
|
|
14
14
|
*/
|
|
15
|
-
export declare function buildEngineServerConfiguration(envVars: IEngineServerEnvironmentVariables
|
|
15
|
+
export declare function buildEngineServerConfiguration(envVars: IEngineServerEnvironmentVariables & {
|
|
16
|
+
[id: string]: string | unknown;
|
|
17
|
+
}, availableContextIdKeys: {
|
|
16
18
|
key: string;
|
|
17
|
-
|
|
19
|
+
requiredHandlerFeatures: string[];
|
|
18
20
|
}[], coreEngineConfig: IEngineCoreConfig, serverInfo: IServerInfo, openApiSpecPath?: string, favIconPath?: string): Promise<IEngineServerConfig>;
|
|
21
|
+
/**
|
|
22
|
+
* Checks if the authentication entity storage subsystem is required.
|
|
23
|
+
* Returns true when any component that depends on the authentication entity storage subsystem is enabled.
|
|
24
|
+
* @param envVars The environment variables.
|
|
25
|
+
* @returns True if authentication entity storage is enabled.
|
|
26
|
+
*/
|
|
27
|
+
export declare function isAuthEntityStorageRequired(envVars: IEngineServerEnvironmentVariables): boolean;
|
|
@@ -12,7 +12,7 @@ export declare function extensionsConfiguration(envVars: INodeEnvironmentVariabl
|
|
|
12
12
|
* Handles the initialisation of the extensions when the engine has been constructed.
|
|
13
13
|
* @param envVars The environment variables for the node.
|
|
14
14
|
* @param engineCore The engine core instance.
|
|
15
|
-
* @returns
|
|
15
|
+
* @returns A promise that resolves when all extension engine initialisation methods have completed.
|
|
16
16
|
*/
|
|
17
17
|
export declare function extensionsInitialiseEngine(envVars: INodeEnvironmentVariables, engineCore: IEngineCore): Promise<void>;
|
|
18
18
|
/**
|
|
@@ -20,13 +20,13 @@ export declare function extensionsInitialiseEngine(envVars: INodeEnvironmentVari
|
|
|
20
20
|
* @param envVars The environment variables for the node.
|
|
21
21
|
* @param engineCore The engine core instance.
|
|
22
22
|
* @param engineServer The engine server instance.
|
|
23
|
-
* @returns
|
|
23
|
+
* @returns A promise that resolves when all extension engine-server initialisation methods have completed.
|
|
24
24
|
*/
|
|
25
25
|
export declare function extensionsInitialiseEngineServer(envVars: INodeEnvironmentVariables, engineCore: IEngineCore, engineServer: IEngineServer): Promise<void>;
|
|
26
26
|
/**
|
|
27
27
|
* Handles the shutdown of the extensions.
|
|
28
28
|
* @param envVars The environment variables for the node.
|
|
29
29
|
* @param engineCore The engine core instance.
|
|
30
|
-
* @returns
|
|
30
|
+
* @returns A promise that resolves when all extension shutdown methods have completed.
|
|
31
31
|
*/
|
|
32
32
|
export declare function shutdownExtensions(envVars: INodeEnvironmentVariables, engineCore: IEngineCore): Promise<void>;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { IEngineCore } from "@twin.org/engine-models";
|
|
2
|
+
import type { ICliArgs } from "./models/ICliArgs.js";
|
|
3
|
+
import type { ICliCommand } from "./models/ICliCommand.js";
|
|
4
|
+
import type { INodeEnvironmentVariables } from "./models/INodeEnvironmentVariables.js";
|
|
5
|
+
/**
|
|
6
|
+
* Parse command line arguments.
|
|
7
|
+
* @param args The command line arguments.
|
|
8
|
+
* @returns The parsed command line arguments.
|
|
9
|
+
*/
|
|
10
|
+
export declare function parseCommandLineArgs(args?: string[]): ICliArgs;
|
|
11
|
+
/**
|
|
12
|
+
* Construct the CLI command from the parsed arguments.
|
|
13
|
+
* @param processEnv The environment variables from the process.
|
|
14
|
+
* @param cliArgs The parsed CLI arguments.
|
|
15
|
+
* @returns The constructed CLI command.
|
|
16
|
+
* @throws GeneralError if the command is missing.
|
|
17
|
+
*/
|
|
18
|
+
export declare function constructCliCommand(processEnv: {
|
|
19
|
+
[id: string]: string;
|
|
20
|
+
}, cliArgs: ICliArgs): ICliCommand | undefined;
|
|
21
|
+
/**
|
|
22
|
+
* Execute the CLI command.
|
|
23
|
+
* @param engineCore The engine core.
|
|
24
|
+
* @param envVars The environment variables for the node.
|
|
25
|
+
* @param cliCommand The CLI command to execute.
|
|
26
|
+
*/
|
|
27
|
+
export declare function executeCommand(engineCore: IEngineCore, envVars: INodeEnvironmentVariables, cliCommand: ICliCommand): Promise<void>;
|
|
28
|
+
/**
|
|
29
|
+
* Load the env files and process the options.
|
|
30
|
+
* @param processEnv The environment variables from the process.
|
|
31
|
+
* @param options The options.
|
|
32
|
+
* @returns The substituted options, mutated in place with env variable values resolved.
|
|
33
|
+
* @throws GeneralError if an env file has errors.
|
|
34
|
+
*/
|
|
35
|
+
export declare function processEnvOptions(processEnv: {
|
|
36
|
+
[id: string]: string;
|
|
37
|
+
}, options: {
|
|
38
|
+
key: string;
|
|
39
|
+
value: string;
|
|
40
|
+
}[]): void;
|
|
41
|
+
/**
|
|
42
|
+
* Process options and replace any env variables with their values.
|
|
43
|
+
* @param processEnv The environment variables from the process.
|
|
44
|
+
* @param options The options.
|
|
45
|
+
* @throws GeneralError if an env variable is missing.
|
|
46
|
+
*/
|
|
47
|
+
export declare function substituteEnvOptions(processEnv: {
|
|
48
|
+
[id: string]: string;
|
|
49
|
+
}, options: {
|
|
50
|
+
key: string;
|
|
51
|
+
value: string;
|
|
52
|
+
}[]): void;
|
|
53
|
+
/**
|
|
54
|
+
* Register all built-in CLI command definitions into the shared command map.
|
|
55
|
+
*/
|
|
56
|
+
export declare function registerCommands(): void;
|