@uns-kit/core 1.0.5 → 1.0.9

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.
Files changed (42) hide show
  1. package/README.md +18 -0
  2. package/dist/tools/generate-uns-dictionary.d.ts +3 -0
  3. package/dist/tools/generate-uns-dictionary.d.ts.map +1 -0
  4. package/dist/tools/generate-uns-dictionary.js +270 -0
  5. package/dist/tools/generate-uns-dictionary.js.map +1 -0
  6. package/dist/tools/initialize.js.map +1 -1
  7. package/dist/tools/update-tools.js.map +1 -1
  8. package/dist/uns/uns-attributes.d.ts +6 -143
  9. package/dist/uns/uns-attributes.d.ts.map +1 -1
  10. package/dist/uns/uns-attributes.js +7 -180
  11. package/dist/uns/uns-attributes.js.map +1 -1
  12. package/dist/uns/uns-dictionary.generated.d.ts +83 -0
  13. package/dist/uns/uns-dictionary.generated.d.ts.map +1 -0
  14. package/dist/uns/uns-dictionary.generated.js +160 -0
  15. package/dist/uns/uns-dictionary.generated.js.map +1 -0
  16. package/dist/uns/uns-interfaces.d.ts +10 -3
  17. package/dist/uns/uns-interfaces.d.ts.map +1 -1
  18. package/dist/uns/uns-interfaces.js.map +1 -1
  19. package/dist/uns/uns-object.d.ts +14 -38
  20. package/dist/uns/uns-object.d.ts.map +1 -1
  21. package/dist/uns/uns-object.js +4 -61
  22. package/dist/uns/uns-object.js.map +1 -1
  23. package/dist/uns/uns-proxy.d.ts +3 -1
  24. package/dist/uns/uns-proxy.d.ts.map +1 -1
  25. package/dist/uns/uns-proxy.js +10 -5
  26. package/dist/uns/uns-proxy.js.map +1 -1
  27. package/dist/uns-grpc/uns-gateway-server.js +1 -1
  28. package/dist/uns-grpc/uns-gateway-server.js.map +1 -1
  29. package/dist/uns-mqtt/uns-mqtt-proxy.d.ts.map +1 -1
  30. package/dist/uns-mqtt/uns-mqtt-proxy.js +5 -2
  31. package/dist/uns-mqtt/uns-mqtt-proxy.js.map +1 -1
  32. package/package.json +1 -1
  33. package/dist/app-config.d.ts.map +0 -1
  34. package/dist/app-config.js.map +0 -1
  35. package/dist/tools/initialize.d.ts +0 -2
  36. package/dist/tools/initialize.js +0 -104
  37. package/dist/tools/make.d.ts +0 -2
  38. package/dist/tools/make.js +0 -28
  39. package/dist/tools/update-rtt.d.ts +0 -2
  40. package/dist/tools/update-rtt.js +0 -170
  41. package/dist/tools/update-tools.d.ts +0 -2
  42. package/dist/tools/update-tools.js +0 -73
@@ -1 +1 @@
1
- {"version":3,"file":"uns-mqtt-proxy.js","sourceRoot":"","sources":["../../src/uns-mqtt/uns-mqtt-proxy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAElC,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,MAAM,MAAM,cAAc,CAAC;AAKlC,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAEjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,QAAQ,MAAM,qBAAqB,CAAC;AAC3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAExD,MAAM,eAAe,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,cAAc,CAAC,CAAC;AAC5D,MAAM,WAAW,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,eAAe,EAAE,MAAM,CAAC,CAAC,CAAC;AAEtE,MAAM,eAAe,GAAG,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AACrE,MAAM,WAAW,GAAG,IAAI,CAAC,OAAO,CAAC,eAAe,EAAE,IAAI,EAAE,IAAI,CA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AAC,OAAO,CAAC,KAAK,EAAE,CAAC;gBACpC,MAAM,IAAI,CAAC,2BAA2B,CAAC,YAAY,EAAE,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;YACnF,CAAC;QACH,CAAC;QAAC,OAAO,KAAU,EAAE,CAAC;YACpB,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,sBAAsB,wCAAwC,GAAG,CAAC,KAAK,GAAG,GAAG,CAAC,SAAS,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;QACpI,CAAC;IACH,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,IAAI;QACf,KAAK,CAAC,IAAI,EAAE,CAAC;QACb,4CAA4C;QAC5C,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,IAAI,CAAC;gBACH,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC;gBAC/C,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,sBAAsB,uCAAuC,QAAQ,EAAE,CAAC,CAAC;YAC/F,CAAC;YAAC,OAAO,KAAU,EAAE,CAAC;gBACpB,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,sBAAsB,gCAAgC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;YAC9F,CAAC;QACH,CAAC;QAED,2CAA2C;QAC3C,KAAK,MAAM,CAAC,EAAE,EAAE,OAAO,CAAC,IAAI,IAAI,CAAC,eAAe,EAAE,CAAC;YACjD,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC,CAAC;YACvD,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QAClC,CAAC;IACH,CAAC;CAEF","sourcesContent":["import { readFileSync } from \"fs\";\nimport { IClientPublishOptions } from \"mqtt\";\nimport * as path from \"path\";\nimport { Worker } from \"worker_threads\";\nimport { fileURLToPath } from \"url\";\nimport { basePath } from \"../base-path.js\";\nimport logger from \"../logger.js\";\nimport { IMqttMessage, IUnsPacket, IUnsParameters, UnsEvents, ValueType } from \"../uns/uns-interfaces.js\";\nimport type { UnsObjectId, UnsObjectType } from \"../uns/uns-object.js\";\nimport type { UnsAsset } from \"../uns/uns-asset.js\";\nimport { MeasurementUnit } from \"../uns/uns-measurements.js\";\nimport { UnsPacket } from \"../uns/uns-packet.js\";\nimport { IMqttParameters, IMqttWorkerData } from \"./mqtt-interfaces.js\";\nimport { MqttTopicBuilder } from \"./mqtt-topic-builder.js\";\nimport UnsProxy from \"../uns/uns-proxy.js\";\nimport { UnsAttributeType } from \"../graphql/schema.js\";\n\nconst packageJsonPath = path.join(basePath, \"package.json\");\nconst packageJson = JSON.parse(readFileSync(packageJsonPath, \"utf8\"));\n\nconst moduleDirectory = path.dirname(fileURLToPath(import.meta.url));\nconst packageRoot = path.resolve(moduleDirectory, \"..\", \"..\");\nconst workerScriptPath = path.join(packageRoot, \"dist/uns-mqtt/mqtt-worker-init.js\");\n\nexport enum MessageMode {\n Raw = 'raw', // Send only the original message\n Delta = 'delta', // Send only the delta message\n Both = 'both' // Send both the original and delta messages\n}\n\nexport default class UnsMqttProxy extends UnsProxy {\n private lastValues: Map<string, { value: ValueType; uom: string; timestamp: Date }> = new Map();\n private worker: Worker;\n private pendingEnqueues: Map<string, { resolve: () => void; reject: (reason?: any) => void }> = new Map();\n private unsParameters: IUnsParameters;\n protected processStatusTopic: string;\n public instanceName: string;\n private currentSequenceId: Map<string, number> = new Map();\n private topicBuilder: MqttTopicBuilder;\n\n constructor(\n mqttHost: string,\n processName: string,\n instanceName: string,\n unsParameters?: IUnsParameters,\n publisherActive: boolean = false,\n subscriberActive: boolean = false\n ) {\n super();\n this.instanceName = instanceName;\n // Create the topic builder using packageJson values and the processName.\n this.topicBuilder = new MqttTopicBuilder(`uns-infra/${MqttTopicBuilder.sanitizeTopicPart(packageJson.name)}/${MqttTopicBuilder.sanitizeTopicPart(packageJson.version)}/${MqttTopicBuilder.sanitizeTopicPart(processName)}/`);\n\n // Generate the processStatusTopic using the builder.\n this.processStatusTopic = this.topicBuilder.getProcessStatusTopic();\n // Derive the instanceStatusTopic by appending the instance name.\n this.instanceStatusTopic = this.processStatusTopic + instanceName + \"/\";\n\n // Concatenate processName with instanceName for the worker identification.\n this.instanceNameWithSuffix = `${processName}-${instanceName}`;\n \n const mqttParameters: IMqttParameters = {\n mqttSubToTopics: unsParameters?.mqttSubToTopics ?? [],\n username: unsParameters?.username ?? \"\",\n password: unsParameters?.password ?? \"\",\n mqttSSL: unsParameters?.mqttSSL ?? false,\n statusTopic: this.instanceStatusTopic,\n };\n this.unsParameters = unsParameters ?? {};\n this.startQueueWorker(mqttHost, this.instanceNameWithSuffix, mqttParameters, publisherActive, subscriberActive);\n }\n\n /**\n * Resolve object identity from explicit fields or the tail of the topic path.\n * Falls back to parsing when not provided for backward compatibility.\n */\n private resolveObjectIdentity(msg: IMqttMessage): { objectType?: UnsObjectType; objectId?: UnsObjectId; asset?: UnsAsset } {\n const providedType = msg.objectType;\n const providedId = msg.objectId;\n const providedAsset = msg.asset;\n\n const topicParts = msg.topic.split(\"/\").filter((part) => part.length > 0);\n const hasObjectTail = topicParts.length >= 2;\n const parsedType = hasObjectTail ? topicParts[topicParts.length - 2] as UnsObjectType : undefined;\n const parsedId = hasObjectTail ? topicParts[topicParts.length - 1] as UnsObjectId : undefined;\n const parsedAsset = hasObjectTail\n ? (topicParts.length >= 3 ? topicParts[topicParts.length - 3] as UnsAsset : undefined)\n : (topicParts.length >= 1 ? topicParts[topicParts.length - 1] as UnsAsset : undefined);\n\n const objectType = providedType ?? parsedType;\n const objectId = providedId ?? parsedId ?? \"main\";\n const asset = providedAsset ?? parsedAsset;\n\n // If values are provided, trust them; otherwise derive from topic.\n if (!providedType || !providedId) {\n if (parsedType && parsedId) {\n logger.warn(`${this.instanceNameWithSuffix} - objectType/objectId missing; derived from topic tail ${parsedType}/${parsedId}`);\n } else {\n logger.warn(`${this.instanceNameWithSuffix} - objectType/objectId missing; defaulting objectId to 'main' for topic '${msg.topic}'. Expected topic to end with '<objectType>/<objectId>/'`);\n }\n }\n // Asset is optional; no warning on mismatch to avoid noisy logs when base topics don't carry it.\n\n msg.objectType = objectType;\n msg.objectId = objectId;\n msg.asset = asset;\n\n return { objectType, objectId, asset };\n }\n\n /**\n * Ensure the topic ends with a trailing slash for attribute concatenation.\n */\n private normalizeTopicWithObject(topic: string): string {\n return topic.endsWith(\"/\") ? topic : `${topic}/`;\n }\n\n /**\n * Starts a worker thread to process the throttled publish queue.\n */\n private startQueueWorker(\n mqttHost: string,\n instanceNameWithSuffix: string,\n mqttParameters: IMqttParameters,\n publisherActive: boolean,\n subscriberActive: boolean\n ): void {\n const workerData: IMqttWorkerData = {\n publishThrottlingDelay: this.unsParameters.publishThrottlingDelay ?? 1,\n subscribeThrottlingDelay: this.unsParameters.subscribeThrottlingDelay ?? 1,\n persistToDisk: false,\n mqttHost: mqttHost,\n instanceNameWithSuffix: instanceNameWithSuffix,\n mqttParameters: mqttParameters,\n publisherActive,\n subscriberActive\n };\n\n this.worker = new Worker(workerScriptPath, { workerData });\n\n this.worker.on(\"message\", (msg) => {\n if (msg && msg.command === \"enqueueResult\" && msg.id) {\n const pending = this.pendingEnqueues.get(msg.id);\n if (pending) {\n if (msg.status === \"success\" && msg.topic && msg.message) {\n pending.resolve();\n } else {\n pending.reject(new Error(msg.error));\n }\n this.pendingEnqueues.delete(msg.id);\n }\n } else if (msg && msg.command === \"input\") {\n this.event.emit(\"input\", { topic: msg.topic, message: msg.message.toString(), packet: msg.packet });\n } else if (msg && (msg.command === \"handover_subscriber\" || msg.command === \"handover_publisher\")) {\n this.event.emit(\"mqttWorker\", { command: msg.command, batchSize: msg.batchSize, referenceHash: msg.referenceHash, instanceName: this.instanceName });\n } else if (msg && msg.command === \"mqttProxyStatus\") {\n this.event.emit(\"mqttProxyStatus\", { event: msg.event, value: msg.value, uom: msg.uom, statusTopic: msg.statusTopic });\n }\n });\n\n this.worker.on(\"error\", (err) => {\n logger.error(\"Error in worker:\", err);\n });\n\n this.worker.on(\"exit\", (code) => {\n if (code !== 0) {\n logger.error(`Worker exited with code ${code}`);\n }\n });\n }\n\n /**\n * Enqueues a message to the worker queue.\n *\n * @param topic - The topic to which the message belongs.\n * @param message - The message to be enqueued.\n * @param options - Optional publish options.\n * @returns A promise that resolves when the message is successfully enqueued.\n */\n private async enqueueMessageToWorkerQueue(topic: string, message: string, options?: IClientPublishOptions): Promise<void> {\n return new Promise((resolve, reject) => {\n // const id: string = String(this.currentSequenceId.get(topic) ?? 0);\n const id = `${Date.now()}-${Math.random()}`;\n this.pendingEnqueues.set(id, { resolve, reject });\n this.worker.postMessage({ command: \"enqueue\", id, topic, message, options });\n });\n }\n\n /**\n * Sets the publisher active state.\n *\n * @param batchSize - Optional batch size.\n * @param referenceHash - Optional reference hash.\n */\n public setPublisherActive(batchSize?: number, referenceHash?: string): void {\n this.worker.postMessage({ command: \"setPublisherActive\", batchSize, referenceHash });\n }\n\n /**\n * Sets the publisher to passive mode.\n * @returns A promise that resolves when the publisher is set to passive.\n */\n public setPublisherPassive(): Promise<UnsEvents[\"mqttWorker\"]> {\n this.worker.postMessage({ command: \"setPublisherPassive\"});\n return new Promise((resolve) => {\n this.event.on(\"mqttWorker\", (msg: UnsEvents[\"mqttWorker\"]) => {\n if (msg.command === \"handover_publisher\") {\n logger.info(`${this.instanceNameWithSuffix} - Publisher set to passive.`);\n resolve(msg);\n }\n });\n });\n }\n\n /**\n * Sets the subscriber active state.\n *\n * @param batchSize - Optional batch size.\n * @param referenceHash - Optional reference hash.\n */\n public setSubscriberActive(batchSize?: number, referenceHash?: string): void {\n this.worker.postMessage({ command: \"setSubscriberActive\", batchSize, referenceHash });\n }\n\n /**\n * Sets the subscriber to passive mode.\n * @returns A promise that resolves when the subscriber is set to passive.\n */\n public setSubscriberPassive(): Promise<UnsEvents[\"mqttWorker\"]> {\n this.worker.postMessage({ command: \"setSubscriberPassive\"});\n return new Promise((resolve) => {\n this.event.on(\"mqttWorker\", (msg: UnsEvents[\"mqttWorker\"]) => {\n if (msg.command === \"handover_subscriber\") {\n logger.info(`${this.instanceNameWithSuffix} - Publisher set to passive.`);\n resolve(msg);\n }\n });\n });\n }\n\n\n /**\n * Sets the subscriber to passive mode and allows the publisher to run\n * until the queue is empty (all messages are processed).\n */\n public async setSubscriberPassiveAndDrainQueue(): Promise<UnsEvents[\"mqttWorker\"]> {\n return new Promise(async (resolve) => {\n const mqttWorkerData = await this.setSubscriberPassive();\n while (this.pendingEnqueues.size > 0) {\n await new Promise((resolve) => setTimeout(resolve, 100)); // Poll every 100ms\n }\n logger.info(`${this.instanceNameWithSuffix} - Subscriber set to passive and queue drained.`);\n resolve(mqttWorkerData);\n });\n }\n\n /**\n * Processes and publishes MQTT messages based on the selected message mode.\n *\n * @param mqttMessage - The MQTT message object.\n * @param mode - The message mode (Raw, Delta, or Both).\n */\n public publishMqttMessage(mqttMessage: IMqttMessage | null, mode: MessageMode = MessageMode.Raw) {\n if (mqttMessage) {\n if (mqttMessage.packet) {\n const time = UnsPacket.formatToISO8601(new Date());\n switch (mode) {\n case MessageMode.Raw: {\n this.processAndEnqueueMessage(mqttMessage, time, false);\n break;\n }\n case MessageMode.Delta: {\n const deltaMessage = { ...mqttMessage };\n deltaMessage.attribute = `${mqttMessage.attribute}-delta`;\n deltaMessage.description = `${mqttMessage.description} (delta)`;\n this.processAndEnqueueMessage(deltaMessage, time, true);\n break;\n }\n case MessageMode.Both: {\n this.processAndEnqueueMessage(mqttMessage, time, false);\n const deltaMessageBoth = { ...mqttMessage };\n deltaMessageBoth.attribute = `${mqttMessage.attribute}-delta`;\n deltaMessageBoth.description = `${mqttMessage.description} (delta)`;\n this.processAndEnqueueMessage(deltaMessageBoth, time, true);\n break;\n }\n } \n } else {\n logger.error(`${this.instanceNameWithSuffix} - Error publishing mqtt message: mqttMessage.packet must be defined.`);\n }\n } else {\n logger.error(`${this.instanceNameWithSuffix} - Error publishing mqtt message: mqttMessage must be defined.`);\n }\n }\n\n /**\n * Publishes a message to a specified topic.\n *\n * @param topic - The MQTT topic.\n * @param message - The message to publish.\n * @returns A promise that resolves when enqueued.\n */\n public publishMessage(topic: string, message: string): Promise<void> {\n return this.enqueueMessageToWorkerQueue(topic, message);\n }\n\n /**\n * Parses an MQTT packet from a JSON string.\n *\n * @param mqttPacket - The MQTT packet string.\n * @returns A parsed IUnsPacket object or null.\n */\n public parseMqttPacket(mqttPacket: string): IUnsPacket | null {\n return UnsPacket.parseMqttPacket(mqttPacket, this.instanceNameWithSuffix);\n }\n\n /**\n * Subscribes asynchronously to one or more topics.\n *\n * @param topics - A topic or list of topics.\n */\n public subscribeAsync(topics: string | string[]): void {\n this.worker.postMessage({ command: \"subscribeAsync\", topics });\n }\n\n /**\n * Unsubscribes asynchronously from the given topics.\n *\n * @param topics - A list of topics.\n */\n public unsubscribeAsync(topics: string[]): void {\n this.worker.postMessage({ command: \"unsubscribeAsync\", topics });\n }\n\n /**\n * Processes and enqueues a message to the worker queue, including handling\n * sequencing, value differences, and tracking of unique topics.\n *\n * @param msg - The MQTT message to process.\n * @param time - The timestamp.\n * @param valueIsCumulative - Whether the value is cumulative.\n */\n private async processAndEnqueueMessage(msg: IMqttMessage, time: string, valueIsCumulative: boolean = false): Promise<void> {\n try {\n const attributeType =\n msg.packet.message.data ? UnsAttributeType.Data :\n msg.packet.message.event ? UnsAttributeType.Event :\n msg.packet.message.table ? UnsAttributeType.Table : null;\n \n let dataGroup = \"\";\n if (attributeType == UnsAttributeType.Data)\n dataGroup = msg.packet.message.data.dataGroup ?? \"\";\n if (attributeType == UnsAttributeType.Table)\n dataGroup = msg.packet.message.table.dataGroup ?? \"\";\n if (attributeType == UnsAttributeType.Event)\n dataGroup = msg.packet.message.event.dataGroup ?? \"\";\n\n const { objectType, objectId, asset } = this.resolveObjectIdentity(msg);\n const normalizedTopic = this.normalizeTopicWithObject(msg.topic);\n msg.topic = normalizedTopic;\n\n this.registerUniqueTopic({\n timestamp: time,\n topic: msg.topic,\n attribute: msg.attribute,\n attributeType: attributeType,\n description: msg.description,\n tags: msg.tags,\n attributeNeedsPersistence: msg.attributeNeedsPersistence,\n dataGroup,\n asset,\n objectType,\n objectId\n });\n\n const publishTopic = `${msg.topic}${objectType ? `${objectType}/` : \"\"}${objectId ? `${objectId}/` : \"\"}${msg.attribute}`;\n const sequenceId = this.currentSequenceId.get(msg.topic) ?? 0;\n this.currentSequenceId.set(msg.topic, sequenceId + 1);\n msg.packet.sequenceId = sequenceId;\n\n if (msg.packet.message.data) {\n const newValue = msg.packet.message.data.value;\n const newUom: MeasurementUnit = msg.packet.message.data.uom;\n const lastValueEntry = this.lastValues.get(publishTopic);\n const currentTime = new Date(msg.packet.message.data.time);\n\n if (lastValueEntry) {\n const intervalBetweenMessages = currentTime.getTime() - lastValueEntry.timestamp.getTime();\n const lastValue = lastValueEntry.value;\n this.lastValues.set(publishTopic, { value: newValue, uom: newUom, timestamp: currentTime });\n // Compute the delta and manage cumulative resets\n if (valueIsCumulative == true && typeof newValue === \"number\" && typeof lastValue === \"number\") {\n // Skip if newValue is 0 (likely a glitch)\n if (newValue === 0) {\n return; // Don't process or enqueue\n }\n const delta = newValue - lastValue;\n msg.packet.message.data.value = delta < 0 ? newValue : delta;\n }\n msg.packet.interval = intervalBetweenMessages;\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n } else {\n this.lastValues.set(publishTopic, { value: newValue, uom: newUom, timestamp: currentTime });\n logger.debug(`${this.instanceNameWithSuffix} - Need one more packet to calculate interval on topic ${publishTopic}`);\n if (valueIsCumulative === false) {\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n } else {\n logger.debug(`${this.instanceNameWithSuffix} - Need one more packet to calculate difference on value in data for topic ${publishTopic}`);\n }\n }\n } else if (msg.packet.message.command) {\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n } else if (msg.packet.message.event) {\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n } else if (msg.packet.message.table) {\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n }\n } catch (error: any) {\n logger.error(`${this.instanceNameWithSuffix} - Error publishing message to topic ${msg.topic}${msg.attribute}: ${error.message}`);\n }\n }\n\n /**\n * Stops the UnsProxy instance and cleans up resources.\n */\n public async stop(): Promise<void> {\n super.stop();\n // Terminate the worker thread if it exists.\n if (this.worker) {\n try {\n const exitCode = await this.worker.terminate();\n logger.info(`${this.instanceNameWithSuffix} - Worker terminated with exit code ${exitCode}`);\n } catch (error: any) {\n logger.error(`${this.instanceNameWithSuffix} - Error terminating worker: ${error.message}`);\n }\n }\n \n // Optionally, handle any pending enqueues.\n for (const [id, pending] of this.pendingEnqueues) {\n pending.reject(new Error(\"UnsProxy has been stopped\"));\n this.pendingEnqueues.delete(id);\n }\n }\n\n}\n"]}
1
+ {"version":3,"file":"uns-mqtt-proxy.js","sourceRoot":"","sources":["../../src/uns-mqtt/uns-mqtt-proxy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAElC,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,MAAM,MAAM,cAAc,CAAC;AAKlC,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAEjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,QAAQ,MAAM,qBAAqB,CAAC;AAC3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAExD,MAAM,eAAe,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE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AAM,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,sBAAsB,gCAAgC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;YAC9F,CAAC;QACH,CAAC;QAED,2CAA2C;QAC3C,KAAK,MAAM,CAAC,EAAE,EAAE,OAAO,CAAC,IAAI,IAAI,CAAC,eAAe,EAAE,CAAC;YACjD,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC,CAAC;YACvD,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QAClC,CAAC;IACH,CAAC;CAEF","sourcesContent":["import { readFileSync } from \"fs\";\nimport { IClientPublishOptions } from \"mqtt\";\nimport * as path from \"path\";\nimport { Worker } from \"worker_threads\";\nimport { fileURLToPath } from \"url\";\nimport { basePath } from \"../base-path.js\";\nimport logger from \"../logger.js\";\nimport { IMqttMessage, IUnsPacket, IUnsParameters, UnsEvents, ValueType } from \"../uns/uns-interfaces.js\";\nimport type { UnsObjectId, UnsObjectType } from \"../uns/uns-object.js\";\nimport type { UnsAsset } from \"../uns/uns-asset.js\";\nimport { MeasurementUnit } from \"../uns/uns-measurements.js\";\nimport { UnsPacket } from \"../uns/uns-packet.js\";\nimport { IMqttParameters, IMqttWorkerData } from \"./mqtt-interfaces.js\";\nimport { MqttTopicBuilder } from \"./mqtt-topic-builder.js\";\nimport UnsProxy from \"../uns/uns-proxy.js\";\nimport { UnsAttributeType } from \"../graphql/schema.js\";\n\nconst packageJsonPath = path.join(basePath, \"package.json\");\nconst packageJson = JSON.parse(readFileSync(packageJsonPath, \"utf8\"));\n\nconst moduleDirectory = path.dirname(fileURLToPath(import.meta.url));\nconst packageRoot = path.resolve(moduleDirectory, \"..\", \"..\");\nconst workerScriptPath = path.join(packageRoot, \"dist/uns-mqtt/mqtt-worker-init.js\");\n\nexport enum MessageMode {\n Raw = 'raw', // Send only the original message\n Delta = 'delta', // Send only the delta message\n Both = 'both' // Send both the original and delta messages\n}\n\nexport default class UnsMqttProxy extends UnsProxy {\n private lastValues: Map<string, { value: ValueType; uom: string; timestamp: Date }> = new Map();\n private worker: Worker;\n private pendingEnqueues: Map<string, { resolve: () => void; reject: (reason?: any) => void }> = new Map();\n private unsParameters: IUnsParameters;\n protected processStatusTopic: string;\n public instanceName: string;\n private currentSequenceId: Map<string, number> = new Map();\n private topicBuilder: MqttTopicBuilder;\n\n constructor(\n mqttHost: string,\n processName: string,\n instanceName: string,\n unsParameters?: IUnsParameters,\n publisherActive: boolean = false,\n subscriberActive: boolean = false\n ) {\n super();\n this.instanceName = instanceName;\n // Create the topic builder using packageJson values and the processName.\n this.topicBuilder = new MqttTopicBuilder(`uns-infra/${MqttTopicBuilder.sanitizeTopicPart(packageJson.name)}/${MqttTopicBuilder.sanitizeTopicPart(packageJson.version)}/${MqttTopicBuilder.sanitizeTopicPart(processName)}/`);\n\n // Generate the processStatusTopic using the builder.\n this.processStatusTopic = this.topicBuilder.getProcessStatusTopic();\n // Derive the instanceStatusTopic by appending the instance name.\n this.instanceStatusTopic = this.processStatusTopic + instanceName + \"/\";\n\n // Concatenate processName with instanceName for the worker identification.\n this.instanceNameWithSuffix = `${processName}-${instanceName}`;\n \n const mqttParameters: IMqttParameters = {\n mqttSubToTopics: unsParameters?.mqttSubToTopics ?? [],\n username: unsParameters?.username ?? \"\",\n password: unsParameters?.password ?? \"\",\n mqttSSL: unsParameters?.mqttSSL ?? false,\n statusTopic: this.instanceStatusTopic,\n };\n this.unsParameters = unsParameters ?? {};\n this.startQueueWorker(mqttHost, this.instanceNameWithSuffix, mqttParameters, publisherActive, subscriberActive);\n }\n\n /**\n * Resolve object identity from explicit fields or the tail of the topic path.\n * Falls back to parsing when not provided for backward compatibility.\n */\n private resolveObjectIdentity(msg: IMqttMessage): { objectType?: UnsObjectType; objectId?: UnsObjectId; asset?: UnsAsset } {\n const providedType = msg.objectType;\n const providedId = msg.objectId;\n const providedAsset = msg.asset;\n\n const topicParts = msg.topic.split(\"/\").filter((part) => part.length > 0);\n const hasObjectTail = topicParts.length >= 2;\n const parsedType = hasObjectTail ? topicParts[topicParts.length - 2] as UnsObjectType : undefined;\n const parsedId = hasObjectTail ? topicParts[topicParts.length - 1] as UnsObjectId : undefined;\n const parsedAsset = hasObjectTail\n ? (topicParts.length >= 3 ? topicParts[topicParts.length - 3] as UnsAsset : undefined)\n : (topicParts.length >= 1 ? topicParts[topicParts.length - 1] as UnsAsset : undefined);\n\n const objectType = providedType ?? parsedType;\n const objectId = providedId ?? parsedId ?? \"main\";\n const asset = providedAsset ?? parsedAsset;\n\n // If values are provided, trust them; otherwise derive from topic.\n if (!providedType || !providedId) {\n if (parsedType && parsedId) {\n logger.warn(`${this.instanceNameWithSuffix} - objectType/objectId missing; derived from topic tail ${parsedType}/${parsedId}`);\n } else {\n logger.warn(`${this.instanceNameWithSuffix} - objectType/objectId missing; defaulting objectId to 'main' for topic '${msg.topic}'. Expected topic to end with '<objectType>/<objectId>/'`);\n }\n }\n // Asset is optional; no warning on mismatch to avoid noisy logs when base topics don't carry it.\n\n msg.objectType = objectType;\n msg.objectId = objectId;\n msg.asset = asset;\n\n return { objectType, objectId, asset };\n }\n\n /**\n * Ensure the topic ends with a trailing slash for attribute concatenation.\n */\n private normalizeTopicWithObject(topic: string): string {\n return topic.endsWith(\"/\") ? topic : `${topic}/`;\n }\n\n /**\n * Starts a worker thread to process the throttled publish queue.\n */\n private startQueueWorker(\n mqttHost: string,\n instanceNameWithSuffix: string,\n mqttParameters: IMqttParameters,\n publisherActive: boolean,\n subscriberActive: boolean\n ): void {\n const workerData: IMqttWorkerData = {\n publishThrottlingDelay: this.unsParameters.publishThrottlingDelay ?? 1,\n subscribeThrottlingDelay: this.unsParameters.subscribeThrottlingDelay ?? 1,\n persistToDisk: false,\n mqttHost: mqttHost,\n instanceNameWithSuffix: instanceNameWithSuffix,\n mqttParameters: mqttParameters,\n publisherActive,\n subscriberActive\n };\n\n this.worker = new Worker(workerScriptPath, { workerData });\n\n this.worker.on(\"message\", (msg) => {\n if (msg && msg.command === \"enqueueResult\" && msg.id) {\n const pending = this.pendingEnqueues.get(msg.id);\n if (pending) {\n if (msg.status === \"success\" && msg.topic && msg.message) {\n pending.resolve();\n } else {\n pending.reject(new Error(msg.error));\n }\n this.pendingEnqueues.delete(msg.id);\n }\n } else if (msg && msg.command === \"input\") {\n this.event.emit(\"input\", { topic: msg.topic, message: msg.message.toString(), packet: msg.packet });\n } else if (msg && (msg.command === \"handover_subscriber\" || msg.command === \"handover_publisher\")) {\n this.event.emit(\"mqttWorker\", { command: msg.command, batchSize: msg.batchSize, referenceHash: msg.referenceHash, instanceName: this.instanceName });\n } else if (msg && msg.command === \"mqttProxyStatus\") {\n this.event.emit(\"mqttProxyStatus\", { event: msg.event, value: msg.value, uom: msg.uom, statusTopic: msg.statusTopic });\n }\n });\n\n this.worker.on(\"error\", (err) => {\n logger.error(\"Error in worker:\", err);\n });\n\n this.worker.on(\"exit\", (code) => {\n if (code !== 0) {\n logger.error(`Worker exited with code ${code}`);\n }\n });\n }\n\n /**\n * Enqueues a message to the worker queue.\n *\n * @param topic - The topic to which the message belongs.\n * @param message - The message to be enqueued.\n * @param options - Optional publish options.\n * @returns A promise that resolves when the message is successfully enqueued.\n */\n private async enqueueMessageToWorkerQueue(topic: string, message: string, options?: IClientPublishOptions): Promise<void> {\n return new Promise((resolve, reject) => {\n // const id: string = String(this.currentSequenceId.get(topic) ?? 0);\n const id = `${Date.now()}-${Math.random()}`;\n this.pendingEnqueues.set(id, { resolve, reject });\n this.worker.postMessage({ command: \"enqueue\", id, topic, message, options });\n });\n }\n\n /**\n * Sets the publisher active state.\n *\n * @param batchSize - Optional batch size.\n * @param referenceHash - Optional reference hash.\n */\n public setPublisherActive(batchSize?: number, referenceHash?: string): void {\n this.worker.postMessage({ command: \"setPublisherActive\", batchSize, referenceHash });\n }\n\n /**\n * Sets the publisher to passive mode.\n * @returns A promise that resolves when the publisher is set to passive.\n */\n public setPublisherPassive(): Promise<UnsEvents[\"mqttWorker\"]> {\n this.worker.postMessage({ command: \"setPublisherPassive\"});\n return new Promise((resolve) => {\n this.event.on(\"mqttWorker\", (msg: UnsEvents[\"mqttWorker\"]) => {\n if (msg.command === \"handover_publisher\") {\n logger.info(`${this.instanceNameWithSuffix} - Publisher set to passive.`);\n resolve(msg);\n }\n });\n });\n }\n\n /**\n * Sets the subscriber active state.\n *\n * @param batchSize - Optional batch size.\n * @param referenceHash - Optional reference hash.\n */\n public setSubscriberActive(batchSize?: number, referenceHash?: string): void {\n this.worker.postMessage({ command: \"setSubscriberActive\", batchSize, referenceHash });\n }\n\n /**\n * Sets the subscriber to passive mode.\n * @returns A promise that resolves when the subscriber is set to passive.\n */\n public setSubscriberPassive(): Promise<UnsEvents[\"mqttWorker\"]> {\n this.worker.postMessage({ command: \"setSubscriberPassive\"});\n return new Promise((resolve) => {\n this.event.on(\"mqttWorker\", (msg: UnsEvents[\"mqttWorker\"]) => {\n if (msg.command === \"handover_subscriber\") {\n logger.info(`${this.instanceNameWithSuffix} - Publisher set to passive.`);\n resolve(msg);\n }\n });\n });\n }\n\n\n /**\n * Sets the subscriber to passive mode and allows the publisher to run\n * until the queue is empty (all messages are processed).\n */\n public async setSubscriberPassiveAndDrainQueue(): Promise<UnsEvents[\"mqttWorker\"]> {\n return new Promise(async (resolve) => {\n const mqttWorkerData = await this.setSubscriberPassive();\n while (this.pendingEnqueues.size > 0) {\n await new Promise((resolve) => setTimeout(resolve, 100)); // Poll every 100ms\n }\n logger.info(`${this.instanceNameWithSuffix} - Subscriber set to passive and queue drained.`);\n resolve(mqttWorkerData);\n });\n }\n\n /**\n * Processes and publishes MQTT messages based on the selected message mode.\n *\n * @param mqttMessage - The MQTT message object.\n * @param mode - The message mode (Raw, Delta, or Both).\n */\n public publishMqttMessage(mqttMessage: IMqttMessage | null, mode: MessageMode = MessageMode.Raw) {\n if (mqttMessage) {\n if (mqttMessage.packet) {\n const time = UnsPacket.formatToISO8601(new Date());\n switch (mode) {\n case MessageMode.Raw: {\n this.processAndEnqueueMessage(mqttMessage, time, false);\n break;\n }\n case MessageMode.Delta: {\n const deltaMessage = { ...mqttMessage };\n deltaMessage.attribute = `${mqttMessage.attribute}-delta`;\n deltaMessage.description = `${mqttMessage.description} (delta)`;\n this.processAndEnqueueMessage(deltaMessage, time, true);\n break;\n }\n case MessageMode.Both: {\n this.processAndEnqueueMessage(mqttMessage, time, false);\n const deltaMessageBoth = { ...mqttMessage };\n deltaMessageBoth.attribute = `${mqttMessage.attribute}-delta`;\n deltaMessageBoth.description = `${mqttMessage.description} (delta)`;\n this.processAndEnqueueMessage(deltaMessageBoth, time, true);\n break;\n }\n } \n } else {\n logger.error(`${this.instanceNameWithSuffix} - Error publishing mqtt message: mqttMessage.packet must be defined.`);\n }\n } else {\n logger.error(`${this.instanceNameWithSuffix} - Error publishing mqtt message: mqttMessage must be defined.`);\n }\n }\n\n /**\n * Publishes a message to a specified topic.\n *\n * @param topic - The MQTT topic.\n * @param message - The message to publish.\n * @returns A promise that resolves when enqueued.\n */\n public publishMessage(topic: string, message: string): Promise<void> {\n return this.enqueueMessageToWorkerQueue(topic, message);\n }\n\n /**\n * Parses an MQTT packet from a JSON string.\n *\n * @param mqttPacket - The MQTT packet string.\n * @returns A parsed IUnsPacket object or null.\n */\n public parseMqttPacket(mqttPacket: string): IUnsPacket | null {\n return UnsPacket.parseMqttPacket(mqttPacket, this.instanceNameWithSuffix);\n }\n\n /**\n * Subscribes asynchronously to one or more topics.\n *\n * @param topics - A topic or list of topics.\n */\n public subscribeAsync(topics: string | string[]): void {\n this.worker.postMessage({ command: \"subscribeAsync\", topics });\n }\n\n /**\n * Unsubscribes asynchronously from the given topics.\n *\n * @param topics - A list of topics.\n */\n public unsubscribeAsync(topics: string[]): void {\n this.worker.postMessage({ command: \"unsubscribeAsync\", topics });\n }\n\n /**\n * Processes and enqueues a message to the worker queue, including handling\n * sequencing, value differences, and tracking of unique topics.\n *\n * @param msg - The MQTT message to process.\n * @param time - The timestamp.\n * @param valueIsCumulative - Whether the value is cumulative.\n */\n private async processAndEnqueueMessage(msg: IMqttMessage, time: string, valueIsCumulative: boolean = false): Promise<void> {\n try {\n const attributeType =\n msg.packet.message.data ? UnsAttributeType.Data :\n msg.packet.message.event ? UnsAttributeType.Event :\n msg.packet.message.table ? UnsAttributeType.Table : null;\n \n let dataGroup = \"\";\n if (attributeType == UnsAttributeType.Data)\n dataGroup = msg.packet.message.data.dataGroup ?? \"\";\n if (attributeType == UnsAttributeType.Table)\n dataGroup = msg.packet.message.table.dataGroup ?? \"\";\n if (attributeType == UnsAttributeType.Event)\n dataGroup = msg.packet.message.event.dataGroup ?? \"\";\n\n const { objectType, objectId, asset } = this.resolveObjectIdentity(msg);\n const normalizedTopic = this.normalizeTopicWithObject(msg.topic);\n msg.topic = normalizedTopic;\n const description = msg.description ?? \"\";\n\n this.registerUniqueTopic({\n timestamp: time,\n topic: msg.topic,\n attribute: msg.attribute,\n attributeType: attributeType,\n description,\n tags: msg.tags,\n attributeNeedsPersistence: msg.attributeNeedsPersistence,\n dataGroup,\n asset,\n assetDescription: msg.assetDescription,\n objectType,\n objectTypeDescription: msg.objectTypeDescription,\n objectId\n });\n\n const publishTopic = `${msg.topic}${asset ? `${asset}/` : \"\"}${objectType ? `${objectType}/` : \"\"}${objectId ? `${objectId}/` : \"\"}${msg.attribute}`;\n const sequenceId = this.currentSequenceId.get(msg.topic) ?? 0;\n this.currentSequenceId.set(msg.topic, sequenceId + 1);\n msg.packet.sequenceId = sequenceId;\n\n if (msg.packet.message.data) {\n const newValue = msg.packet.message.data.value;\n const newUom: MeasurementUnit = msg.packet.message.data.uom;\n const lastValueEntry = this.lastValues.get(publishTopic);\n const currentTime = new Date(msg.packet.message.data.time);\n\n if (lastValueEntry) {\n const intervalBetweenMessages = currentTime.getTime() - lastValueEntry.timestamp.getTime();\n const lastValue = lastValueEntry.value;\n this.lastValues.set(publishTopic, { value: newValue, uom: newUom, timestamp: currentTime });\n // Compute the delta and manage cumulative resets\n if (valueIsCumulative == true && typeof newValue === \"number\" && typeof lastValue === \"number\") {\n // Skip if newValue is 0 (likely a glitch)\n if (newValue === 0) {\n return; // Don't process or enqueue\n }\n const delta = newValue - lastValue;\n msg.packet.message.data.value = delta < 0 ? newValue : delta;\n }\n msg.packet.interval = intervalBetweenMessages;\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n } else {\n this.lastValues.set(publishTopic, { value: newValue, uom: newUom, timestamp: currentTime });\n logger.debug(`${this.instanceNameWithSuffix} - Need one more packet to calculate interval on topic ${publishTopic}`);\n if (valueIsCumulative === false) {\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n } else {\n logger.debug(`${this.instanceNameWithSuffix} - Need one more packet to calculate difference on value in data for topic ${publishTopic}`);\n }\n }\n } else if (msg.packet.message.command) {\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n } else if (msg.packet.message.event) {\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n } else if (msg.packet.message.table) {\n await this.enqueueMessageToWorkerQueue(publishTopic, JSON.stringify(msg.packet));\n }\n } catch (error: any) {\n logger.error(`${this.instanceNameWithSuffix} - Error publishing message to topic ${msg.topic}${msg.attribute}: ${error.message}`);\n }\n }\n\n /**\n * Stops the UnsProxy instance and cleans up resources.\n */\n public async stop(): Promise<void> {\n super.stop();\n // Terminate the worker thread if it exists.\n if (this.worker) {\n try {\n const exitCode = await this.worker.terminate();\n logger.info(`${this.instanceNameWithSuffix} - Worker terminated with exit code ${exitCode}`);\n } catch (error: any) {\n logger.error(`${this.instanceNameWithSuffix} - Error terminating worker: ${error.message}`);\n }\n }\n \n // Optionally, handle any pending enqueues.\n for (const [id, pending] of this.pendingEnqueues) {\n pending.reject(new Error(\"UnsProxy has been stopped\"));\n this.pendingEnqueues.delete(id);\n }\n }\n\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uns-kit/core",
3
- "version": "1.0.5",
3
+ "version": "1.0.9",
4
4
  "description": "Core utilities and runtime building blocks for UNS-based realtime transformers.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -1 +0,0 @@
1
- {"version":3,"file":"app-config.d.ts","sourceRoot":"","sources":["../src/app-config.ts"],"names":[],"mappings":"AACA,MAAM,MAAM,SAAS,GAAG;IACpB,GAAG,EAAE;QACD,OAAO,EAAE,MAAM,CAAC;QAChB,IAAI,EAAE,MAAM,CAAC;QACb,YAAY,CAAC,EAAE,MAAM,GAAG,OAAO,GAAG,UAAU,CAAC;QAC7C,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;QACjC,QAAQ,CAAC,EAAE,OAAO,CAAC;QACnB,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;QACtC,eAAe,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;QACrC,GAAG,CAAC,EAAE,KAAK,GAAG,SAAS,GAAG,MAAM,GAAG,MAAM,CAAC;KAC7C,CAAC;IACF,KAAK,CAAC,EAAE;QACJ,IAAI,EAAE,MAAM,GAAG,CAAC;YACZ,2CAA2C;YAC3C,QAAQ,EAAE,QAAQ,CAAC;YACnB,uDAAuD;YACvD,KAAK,EAAE,MAAM,CAAC;SACjB,GAAG;YACA,iDAAiD;YACjD,QAAQ,EAAE,UAAU,CAAC;YACrB,wEAAwE;YACxE,GAAG,EAAE,MAAM,CAAC;YACZ,gFAAgF;YAChF,QAAQ,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;YAC/B,6EAA6E;YAC7E,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;SAChC,GAAG;YACA,sDAAsD;YACtD,QAAQ,EAAE,QAAQ,CAAC;YACnB,yDAAyD;YACzD,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;YACzB,+EAA+E;YAC/E,aAAa,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;YACnC,6EAA6E;YAC7E,QAAQ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E,OAAO,GAAG,SAAS,CAAC;YAC/B,4EAA4E;YAC5E,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;YACjC,wEAAwE;YACxE,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;YAC/B,oFAAoF;YACpF,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;SAChC,CAAC,CAAC,GAAG,SAAS,CAAC;QAChB,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;KACjC,CAAC;IACF,MAAM,CAAC,EAAE;QACL,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;QAC9B,YAAY,EAAE,MAAM,CAAC;QACrB,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;KAChC,GAAG,SAAS,CAAC;CACjB,CAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"app-config.js","sourceRoot":"","sources":["../src/app-config.ts"],"names":[],"mappings":"","sourcesContent":["/* Auto-generated. Do not edit by hand. */\nexport type AppConfig = {\n uns: {\n graphql: string;\n rest: string;\n instanceMode?: \"wait\" | \"force\" | \"handover\";\n processName?: string | undefined;\n handover?: boolean;\n jwksWellKnownUrl?: string | undefined;\n kidWellKnownUrl?: string | undefined;\n env?: \"dev\" | \"staging\" | \"test\" | \"prod\";\n };\n input?: {\n host: string | ({\n /** Use the supplied host or IP address. */\n provider: \"inline\";\n /** Host or IP address that should be used directly. */\n value: string;\n } | {\n /** Resolve the host from an external mapping. */\n provider: \"external\";\n /** Identifier used when resolving the host from HostResolverOptions. */\n key: string;\n /** Allow the external host to be missing without throwing during resolution. */\n optional?: boolean | undefined;\n /** Fallback host when optional is true and the external entry is missing. */\n default?: string | undefined;\n } | {\n /** Resolve the host from local network interfaces. */\n provider: \"system\";\n /** Address family to return when scanning interfaces. */\n family?: \"IPv4\" | \"IPv6\";\n /** Specific interface to read (falls back to the first match when omitted). */\n interfaceName?: string | undefined;\n /** Allow the interface lookup to fail without throwing during resolution. */\n optional?: boolean | undefined;\n /** Fallback host/IP when optional is true and no interface matches. */\n default?: string | undefined;\n });\n username?: string | undefined;\n password?: (string | ({\n /** Load the secret from an environment variable. */\n provider: \"env\";\n /** Name of the environment variable to read. */\n key: string;\n /** Allow the variable to be absent without throwing during resolution. */\n optional?: boolean | undefined;\n /** Fallback value when optional is true and the variable is missing. */\n default?: string | undefined;\n } | {\n /** Load the secret from Infisical. */\n provider: \"infisical\";\n /** Secret folder path in Infisical, e.g. '/app/database'. */\n path: string;\n /** Secret key/name inside the given path. */\n key: string;\n /** Allow the secret to be absent without throwing during resolution. */\n optional?: boolean | undefined;\n /** Infisical environment override (defaults to current mode if omitted). */\n environment?: string | undefined;\n /** Optional Infisical project identifier when not using the default. */\n projectId?: string | undefined;\n /** Fallback value when the secret is missing and optional resolution is allowed. */\n default?: string | undefined;\n })) | undefined;\n clientId?: string | undefined;\n } | undefined;\n output?: {\n host: string | ({\n /** Use the supplied host or IP address. */\n provider: \"inline\";\n /** Host or IP address that should be used directly. */\n value: string;\n } | {\n /** Resolve the host from an external mapping. */\n provider: \"external\";\n /** Identifier used when resolving the host from HostResolverOptions. */\n key: string;\n /** Allow the external host to be missing without throwing during resolution. */\n optional?: boolean | undefined;\n /** Fallback host when optional is true and the external entry is missing. */\n default?: string | undefined;\n } | {\n /** Resolve the host from local network interfaces. */\n provider: \"system\";\n /** Address family to return when scanning interfaces. */\n family?: \"IPv4\" | \"IPv6\";\n /** Specific interface to read (falls back to the first match when omitted). */\n interfaceName?: string | undefined;\n /** Allow the interface lookup to fail without throwing during resolution. */\n optional?: boolean | undefined;\n /** Fallback host/IP when optional is true and no interface matches. */\n default?: string | undefined;\n });\n username?: string | undefined;\n password?: (string | ({\n /** Load the secret from an environment variable. */\n provider: \"env\";\n /** Name of the environment variable to read. */\n key: string;\n /** Allow the variable to be absent without throwing during resolution. */\n optional?: boolean | undefined;\n /** Fallback value when optional is true and the variable is missing. */\n default?: string | undefined;\n } | {\n /** Load the secret from Infisical. */\n provider: \"infisical\";\n /** Secret folder path in Infisical, e.g. '/app/database'. */\n path: string;\n /** Secret key/name inside the given path. */\n key: string;\n /** Allow the secret to be absent without throwing during resolution. */\n optional?: boolean | undefined;\n /** Infisical environment override (defaults to current mode if omitted). */\n environment?: string | undefined;\n /** Optional Infisical project identifier when not using the default. */\n projectId?: string | undefined;\n /** Fallback value when the secret is missing and optional resolution is allowed. */\n default?: string | undefined;\n })) | undefined;\n clientId?: string | undefined;\n } | undefined;\n infra: {\n host: string | ({\n /** Use the supplied host or IP address. */\n provider: \"inline\";\n /** Host or IP address that should be used directly. */\n value: string;\n } | {\n /** Resolve the host from an external mapping. */\n provider: \"external\";\n /** Identifier used when resolving the host from HostResolverOptions. */\n key: string;\n /** Allow the external host to be missing without throwing during resolution. */\n optional?: boolean | undefined;\n /** Fallback host when optional is true and the external entry is missing. */\n default?: string | undefined;\n } | {\n /** Resolve the host from local network interfaces. */\n provider: \"system\";\n /** Address family to return when scanning interfaces. */\n family?: \"IPv4\" | \"IPv6\";\n /** Specific interface to read (falls back to the first match when omitted). */\n interfaceName?: string | undefined;\n /** Allow the interface lookup to fail without throwing during resolution. */\n optional?: boolean | undefined;\n /** Fallback host/IP when optional is true and no interface matches. */\n default?: string | undefined;\n });\n username?: string | undefined;\n password?: (string | ({\n /** Load the secret from an environment variable. */\n provider: \"env\";\n /** Name of the environment variable to read. */\n key: string;\n /** Allow the variable to be absent without throwing during resolution. */\n optional?: boolean | undefined;\n /** Fallback value when optional is true and the variable is missing. */\n default?: string | undefined;\n } | {\n /** Load the secret from Infisical. */\n provider: \"infisical\";\n /** Secret folder path in Infisical, e.g. '/app/database'. */\n path: string;\n /** Secret key/name inside the given path. */\n key: string;\n /** Allow the secret to be absent without throwing during resolution. */\n optional?: boolean | undefined;\n /** Infisical environment override (defaults to current mode if omitted). */\n environment?: string | undefined;\n /** Optional Infisical project identifier when not using the default. */\n projectId?: string | undefined;\n /** Fallback value when the secret is missing and optional resolution is allowed. */\n default?: string | undefined;\n })) | undefined;\n clientId?: string | undefined;\n };\n devops?: {\n provider?: string | undefined;\n organization: string;\n project?: string | undefined;\n } | undefined;\n}\n"]}
@@ -1,2 +0,0 @@
1
- export declare const packageJsonPath: string;
2
- //# sourceMappingURL=initialize.d.ts.map
@@ -1,104 +0,0 @@
1
- import * as azdev from "azure-devops-node-api";
2
- import chalk from "chalk";
3
- import { readFile } from "fs/promises";
4
- import readline from "node:readline";
5
- import * as path from "path";
6
- import { CleanOptions, simpleGit } from "simple-git";
7
- import fs from "fs-extra";
8
- import { basePath } from "./base-path.js";
9
- const git = simpleGit("./").clean(CleanOptions.FORCE);
10
- export const packageJsonPath = path.join(basePath, "package.json");
11
- const orgUrl = "https://example-org@dev.azure.com/example-org";
12
- const rl = readline.createInterface({
13
- input: process.stdin,
14
- output: process.stdout,
15
- });
16
- let token = "";
17
- const packageJson = JSON.parse(await readFile(packageJsonPath, "utf8"));
18
- const repoName = packageJson.name;
19
- async function run() {
20
- let repos;
21
- let gitApi;
22
- const project = "example-project";
23
- try {
24
- const authHandler = azdev.getPersonalAccessTokenHandler(token);
25
- const connection = new azdev.WebApi(orgUrl, authHandler);
26
- gitApi = await connection.getGitApi();
27
- repos = await gitApi.getRepositories(project);
28
- }
29
- catch (error) {
30
- console.error("Your AZURE_PAT environment variable has probably expired.");
31
- console.log("Please update your AZURE_PAT environment with a new one on.");
32
- console.log("You can create a new one at[https://dev.azure.com/example-org/_usersSettings/tokens]");
33
- }
34
- if (repos.filter((x) => x.name == repoName).length > 0) {
35
- console.log(chalk.red.bold(`Error: Repository ${repoName} in project ${project} already exists.`));
36
- }
37
- else {
38
- process.stdout.write(`Create ${repoName} in project ${project}`);
39
- try {
40
- await gitApi.createRepository({ name: repoName }, project);
41
- console.log(chalk.green.bold(` ... OK`));
42
- }
43
- catch (error) {
44
- console.error(chalk.red.bold(`\n${error}`));
45
- }
46
- process.stdout.write(`Initialize local git repository on branch master`);
47
- try {
48
- await git.init();
49
- await git.checkoutLocalBranch("master");
50
- await git.add(".");
51
- await git.commit("Initial commit");
52
- console.log(chalk.green.bold(` ... OK`));
53
- }
54
- catch (error) {
55
- console.error(chalk.red.bold(`\n${error}`));
56
- }
57
- process.stdout.write(`Add remote origin.`);
58
- try {
59
- await git.remote([
60
- "add",
61
- "origin",
62
- `git@ssh.dev.azure.com:v3/example-org/example-project/${repoName}`,
63
- ]);
64
- console.log(chalk.green.bold(` ... OK`));
65
- }
66
- catch (error) {
67
- console.error(chalk.red.bold(`\n${error}`));
68
- }
69
- process.stdout.write(`Push master to remote`);
70
- try {
71
- await git.push("origin", "master");
72
- console.log(chalk.green.bold(` ... OK`));
73
- }
74
- catch (error) {
75
- console.error(chalk.red.bold(`\n${error}`));
76
- }
77
- process.stdout.write(`Create default config.json from config-template.json`);
78
- try {
79
- fs.copyFileSync(path.join(basePath, 'config-template.json'), path.join(basePath, 'config.json'));
80
- console.log(chalk.green.bold(` ... OK`));
81
- }
82
- catch (error) {
83
- console.error(chalk.red.bold(`\n${error}`));
84
- }
85
- console.log(chalk.green.bold(`\nNow you can add pipeline for ${repoName} in Azure DevOps pipelines for the project ${project}.`));
86
- }
87
- }
88
- console.log(chalk.green.bold(`Create new RTT: ${repoName}\n`));
89
- const envPat = process.env.AZURE_PAT;
90
- if (envPat && envPat.length > 10) {
91
- rl.close();
92
- console.log("Using PAT from your AZURE_PAT environment");
93
- token = envPat;
94
- run();
95
- }
96
- else {
97
- console.log("Could not find AZURE_PAT environment.");
98
- rl.question(`Please enter your PAT, you can create one at [https://dev.azure.com/example-org/_usersSettings/tokens]: `, (newToken) => {
99
- rl.close();
100
- token = newToken;
101
- run();
102
- });
103
- }
104
- //# sourceMappingURL=initialize.js.map
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=make.d.ts.map
@@ -1,28 +0,0 @@
1
- import fs from "fs-extra";
2
- import { basePath } from "./base-path.js";
3
- import * as path from "path";
4
- import { execSync } from 'child_process';
5
- const binDir = path.join(basePath, 'bin/');
6
- try {
7
- const ua = process.env.npm_config_user_agent || "";
8
- const pm = ua.startsWith("pnpm") ? "pnpm" : ua.startsWith("yarn") ? "yarn" : "npm";
9
- execSync(`${pm} run build`, { stdio: 'inherit' });
10
- fs.rmSync(binDir, {
11
- recursive: true,
12
- force: true,
13
- });
14
- fs.mkdirSync(binDir, { recursive: true });
15
- fs.copyFileSync(path.join(basePath, 'LICENSE'), path.join(binDir, 'LICENSE'));
16
- fs.copyFileSync(path.join(basePath, 'package.json'), path.join(binDir, 'package.json'));
17
- fs.copySync(path.join(basePath, 'dist'), path.join(binDir, 'dist/'));
18
- // After all files are copied, check for ../local-tools/make.js and run it if exists
19
- const localToolsDir = path.resolve(basePath, 'dist/local-tools');
20
- const makeJsPath = path.join(localToolsDir, 'make.js');
21
- if (fs.existsSync(makeJsPath)) {
22
- execSync(`node "${makeJsPath}"`, { stdio: 'inherit' });
23
- }
24
- }
25
- catch (error) {
26
- console.log(`error: ${error}`);
27
- }
28
- //# sourceMappingURL=make.js.map
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=update-rtt.d.ts.map
@@ -1,170 +0,0 @@
1
- import { basePath } from "./base-path.js";
2
- import readline from "node:readline";
3
- import * as path from "path";
4
- import chalk from "chalk";
5
- import { readFile } from "fs/promises";
6
- import fs from "fs-extra";
7
- import * as prettier from "prettier";
8
- const rl = readline.createInterface({
9
- input: process.stdin,
10
- output: process.stdout,
11
- });
12
- const packageJsonPath = path.join(basePath, "package.json");
13
- const packageJson = JSON.parse(await readFile(packageJsonPath, "utf8"));
14
- // Flags
15
- const argv = new Set(process.argv.slice(2));
16
- const DRY_RUN = argv.has("--dry-run") || process.env.DRY_RUN === "1";
17
- function logAction(action) {
18
- if (DRY_RUN)
19
- console.log(`[dry-run] ${action}`);
20
- else
21
- console.log(action);
22
- }
23
- function writeJson(file, obj) {
24
- return prettier.format(JSON.stringify(obj), { parser: "json" }).then((s) => {
25
- if (DRY_RUN) {
26
- console.log(`[dry-run] write ${file} (${s.length} bytes)`);
27
- }
28
- else {
29
- fs.writeFileSync(file, s, "utf8");
30
- }
31
- });
32
- }
33
- function copyDir(src, dest, options) {
34
- if (DRY_RUN) {
35
- console.log(`[dry-run] copy ${src} -> ${dest}`);
36
- return;
37
- }
38
- fs.copySync(src, dest, { overwrite: true, ...options });
39
- }
40
- function removePath(p, opts) {
41
- if (DRY_RUN) {
42
- console.log(`[dry-run] rm ${p}`);
43
- return;
44
- }
45
- fs.rmSync(p, { force: true, recursive: true, ...opts });
46
- }
47
- try {
48
- await main();
49
- rl.close();
50
- }
51
- catch (error) {
52
- console.log(chalk.red.bold(`\n${error}`));
53
- rl.close();
54
- }
55
- async function main() {
56
- const tmpRtt = path.join(basePath, "/tmp-rtt");
57
- try {
58
- logAction(`Overwrite examples`);
59
- copyDir(path.join(tmpRtt, "/src/examples"), path.join(basePath, "/src/examples"));
60
- logAction(`Overwrite uns`);
61
- copyDir(path.join(tmpRtt, "/src/uns"), path.join(basePath, "/src/uns"));
62
- logAction(`Overwrite uns-config`);
63
- copyDir(path.join(tmpRtt, "/src/uns-config"), path.join(basePath, "/src/uns-config"));
64
- // Python: copy template but preserve local project area(s) and environments
65
- // Preserved by default: python/rtt, python/venv, python/.venv, python/__pycache__
66
- const pythonSrc = path.join(tmpRtt, "/python");
67
- const pythonDst = path.join(basePath, "/python");
68
- logAction(`Overwrite python (preserve local, rtt, venv/.venv, __pycache__)`);
69
- copyDir(pythonSrc, pythonDst, {
70
- filter: (src) => {
71
- // Only filter relative to template python root
72
- const rel = path.relative(pythonSrc, src);
73
- if (!rel || rel === "")
74
- return true;
75
- const top = rel.split(path.sep)[0];
76
- const preserved = new Set(["local", "rtt", "venv", ".venv", "__pycache__"]);
77
- return !preserved.has(top);
78
- },
79
- });
80
- logAction(`Overwrite uns-grpc`);
81
- copyDir(path.join(tmpRtt, "/src/uns-grpc"), path.join(basePath, "/packages/uns-core/src/uns-grpc"));
82
- logAction(`Overwrite uns-cron`);
83
- copyDir(path.join(tmpRtt, "/src/uns-cron"), path.join(basePath, "/packages/uns-cron/src"));
84
- logAction(`Overwrite uns-api`);
85
- copyDir(path.join(tmpRtt, "/src/uns-api"), path.join(basePath, "/packages/uns-api/src"));
86
- logAction(`Overwrite uns-mqtt`);
87
- copyDir(path.join(tmpRtt, "/src/uns-mqtt"), path.join(basePath, "/packages/uns-core/src/uns-mqtt"));
88
- logAction(`Overwrite uns-temporal`);
89
- copyDir(path.join(tmpRtt, "/src/uns-temporal"), path.join(basePath, "/packages/uns-temporal/src"));
90
- logAction(`Overwrite eslint.config.mjs`);
91
- copyDir(path.join(tmpRtt, "/eslint.config.mjs"), path.join(basePath, "/eslint.config.mjs"));
92
- logAction(`Overwrite schema.ts`);
93
- copyDir(path.join(tmpRtt, "/src/graphql/schema.ts"), path.join(basePath, "/src/graphql/schema.ts"));
94
- logAction(`Overwrite config-template.json`);
95
- copyDir(path.join(tmpRtt, "/config-template.json"), path.join(basePath, "/config-template.json"));
96
- logAction(`Overwrite vite.config.js`);
97
- copyDir(path.join(tmpRtt, "/vite.config.js"), path.join(basePath, "/vite.config.js"));
98
- logAction(`Overwrite codegen.ts`);
99
- copyDir(path.join(tmpRtt, "/codegen.ts"), path.join(basePath, "/codegen.ts"));
100
- logAction(`Overwrite logger.ts`);
101
- copyDir(path.join(tmpRtt, "/src/logger.ts"), path.join(basePath, "/src/logger.ts"));
102
- }
103
- catch (error) {
104
- console.error(chalk.red.bold(`exec error: ${error}`));
105
- return;
106
- }
107
- try {
108
- logAction(`Merge package.json scripts (template overrides existing keys, preserves extras)`);
109
- const tmpPackageJson = JSON.parse(await readFile(path.join(tmpRtt, 'package.json'), "utf8"));
110
- const currentScripts = packageJson.scripts || {};
111
- const templateScripts = tmpPackageJson.scripts || {};
112
- packageJson.scripts = { ...currentScripts, ...templateScripts };
113
- await writeJson('package.json', packageJson);
114
- }
115
- catch (error) {
116
- console.error(chalk.red.bold(`exec error: ${error}`));
117
- return;
118
- }
119
- try {
120
- console.log(chalk.red(`Update devDependencies: overwrite versions for existing, add missing; preserve extras.`));
121
- const tmpPackageJson = JSON.parse(await readFile(path.join(tmpRtt, 'package.json'), "utf8"));
122
- packageJson.devDependencies = packageJson.devDependencies || {};
123
- for (const [dep, version] of Object.entries(tmpPackageJson.devDependencies || {})) {
124
- packageJson.devDependencies[dep] = version;
125
- }
126
- await writeJson('package.json', packageJson);
127
- }
128
- catch (error) {
129
- console.error(chalk.red.bold(`exec error: ${error}`));
130
- return;
131
- }
132
- try {
133
- console.log(chalk.red(`Update dependencies: keep existing versions; add missing from template.`));
134
- const tmpPackageJson = JSON.parse(await readFile(path.join(tmpRtt, 'package.json'), "utf8"));
135
- packageJson.dependencies = packageJson.dependencies || {};
136
- for (const [dep, version] of Object.entries(tmpPackageJson.dependencies || {})) {
137
- if (!(dep in packageJson.dependencies)) {
138
- packageJson.dependencies[dep] = version;
139
- }
140
- }
141
- await writeJson('package.json', packageJson);
142
- }
143
- catch (error) {
144
- console.error(chalk.red.bold(`exec error: ${error}`));
145
- return;
146
- }
147
- try {
148
- logAction(`Remove obsolete directories and files`);
149
- removePath(path.join(basePath, "/src/mqtt-rtt"));
150
- removePath(path.join(basePath, "/src/uns-rtt"));
151
- removePath(path.join(basePath, "/.eslintignore"));
152
- removePath(path.join(basePath, "/.eslintrc.json"));
153
- removePath(path.join(basePath, "/src/update-rtt.ts"));
154
- removePath(path.join(basePath, "/src/demo"));
155
- }
156
- catch (error) {
157
- console.error(chalk.red.bold(`exec error: ${error}`));
158
- return;
159
- }
160
- try {
161
- logAction(`Remove tmp-rtt`);
162
- removePath(tmpRtt);
163
- }
164
- catch (error) {
165
- console.error(chalk.red.bold(`exec error: ${error}`));
166
- return;
167
- }
168
- console.log(chalk.green.bold("\nRun npm run build to rebuild the project, and remove obsolete directories and files."));
169
- }
170
- //# sourceMappingURL=update-rtt.js.map
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=update-tools.d.ts.map
@@ -1,73 +0,0 @@
1
- import { CleanOptions, simpleGit } from "simple-git";
2
- import { basePath } from "./base-path.js";
3
- import readline from "node:readline";
4
- import * as path from "path";
5
- import chalk from "chalk";
6
- import fs from "fs-extra";
7
- import { execSync } from "child_process";
8
- const rl = readline.createInterface({
9
- input: process.stdin,
10
- output: process.stdout,
11
- });
12
- const git = simpleGit("./").clean(CleanOptions.FORCE);
13
- try {
14
- await main();
15
- rl.close();
16
- }
17
- catch (error) {
18
- console.log(chalk.red.bold(`\n${error}`));
19
- rl.close();
20
- }
21
- async function main() {
22
- const tmpRtt = path.join(basePath, "/tmp-rtt");
23
- try {
24
- console.log(`Pull template-ts-nodejs into tmp-rtt`);
25
- await git.clone("git@ssh.dev.azure.com:v3/example-org/example-project/template-uns-rtt", tmpRtt);
26
- }
27
- catch (error) {
28
- console.error(chalk.red.bold(`exec error: ${error}`));
29
- return;
30
- }
31
- try {
32
- console.log(`Overwrite tools`);
33
- fs.copySync(path.join(tmpRtt, "/src/tools"), path.join(basePath, "/src/tools"), { overwrite: true });
34
- }
35
- catch (error) {
36
- console.error(chalk.red.bold(`exec error: ${error}`));
37
- return;
38
- }
39
- // Update library version JSON at repo root from template
40
- try {
41
- const srcJson = path.join(tmpRtt, 'uns-library.json');
42
- const dstJson = path.join(basePath, 'uns-library.json');
43
- if (fs.existsSync(srcJson)) {
44
- fs.copyFileSync(srcJson, dstJson);
45
- const ver = JSON.parse(fs.readFileSync(srcJson, 'utf8')).version;
46
- console.log(`Updated uns-library.json -> ${ver}`);
47
- }
48
- else {
49
- // Fallback for older templates: synthesize from package.json
50
- const tmpPackageJsonPath = path.join(tmpRtt, 'package.json');
51
- const tmpPackageJson = JSON.parse(fs.readFileSync(tmpPackageJsonPath, 'utf8'));
52
- const payload = JSON.stringify({ name: tmpPackageJson.name, version: tmpPackageJson.version }, null, 2);
53
- fs.writeFileSync(dstJson, payload + "\n", 'utf8');
54
- console.log(`Updated uns-library.json -> ${tmpPackageJson.version}`);
55
- }
56
- }
57
- catch (error) {
58
- console.error(chalk.red.bold(`exec error: ${error}`));
59
- return;
60
- }
61
- try {
62
- console.log(`Running update-rtt from tools`);
63
- // Propagate any CLI args to update-rtt (e.g., --dry-run)
64
- const args = process.argv.slice(2).join(" ");
65
- // Run the TypeScript tool directly to avoid relying on a successful build
66
- execSync(`tsx ./src/tools/update-rtt.ts ${args}`.trim(), { stdio: 'inherit' });
67
- }
68
- catch (error) {
69
- console.error(chalk.red.bold(`exec error: ${error}`));
70
- return;
71
- }
72
- }
73
- //# sourceMappingURL=update-tools.js.map