@bonsae/nrg 0.25.1 → 0.26.0

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 (34) hide show
  1. package/package.json +6 -4
  2. package/server/index.cjs +1413 -2
  3. package/server/resources/nrg-client.js +10 -0
  4. package/test/client/component/config.js +9 -9
  5. package/test/client/component/index.js +230 -42
  6. package/test/client/component/nrg.css +1 -0
  7. package/test/client/component/schemas.js +37 -0
  8. package/test/client/component/setup.js +1473 -198
  9. package/test/client/e2e/index.js +33 -35
  10. package/test/client/unit/index.js +17 -2
  11. package/test/server/integration/index.js +1222 -11
  12. package/test/server/unit/index.js +184 -2
  13. package/types/client.d.ts +1 -1
  14. package/types/server.d.ts +8 -2
  15. package/types/shims/components.d.ts +8 -8
  16. package/types/shims/{client → core/client}/types.d.ts +2 -2
  17. package/types/shims/core/schema-options.d.ts +24 -0
  18. package/types/shims/schema-options.d.ts +17 -17
  19. package/types/test-client-component-schemas.d.ts +73 -0
  20. package/types/test-client-component.d.ts +153 -7
  21. package/types/test-client-unit.d.ts +105 -4
  22. package/types/test-server-integration.d.ts +64 -63
  23. package/types/test-server-unit.d.ts +2 -1
  24. package/vite/index.js +33 -35
  25. /package/types/shims/{client → core/client}/form/components/node-red-config-input.vue.d.ts +0 -0
  26. /package/types/shims/{client → core/client}/form/components/node-red-editor-input.vue.d.ts +0 -0
  27. /package/types/shims/{client → core/client}/form/components/node-red-input-label.vue.d.ts +0 -0
  28. /package/types/shims/{client → core/client}/form/components/node-red-input.vue.d.ts +0 -0
  29. /package/types/shims/{client → core/client}/form/components/node-red-json-schema-form.vue.d.ts +0 -0
  30. /package/types/shims/{client → core/client}/form/components/node-red-select-input.vue.d.ts +0 -0
  31. /package/types/shims/{client → core/client}/form/components/node-red-toggle.vue.d.ts +0 -0
  32. /package/types/shims/{client → core/client}/form/components/node-red-typed-input.vue.d.ts +0 -0
  33. /package/types/shims/{constants.d.ts → core/constants.d.ts} +0 -0
  34. /package/types/shims/{brands.d.ts → core/types.d.ts} +0 -0
package/server/index.cjs CHANGED
@@ -1,2 +1,1413 @@
1
- 'use strict';
2
- module.exports = require("@bonsae/nrg-runtime/server");
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/core/server/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ CompletePortSchema: () => CompletePortSchema,
34
+ ConfigNode: () => ConfigNode,
35
+ ErrorPortSchema: () => ErrorPortSchema,
36
+ IONode: () => IONode,
37
+ Node: () => Node,
38
+ NodeSourceSchema: () => NodeSourceSchema,
39
+ NrgError: () => NrgError,
40
+ SchemaType: () => SchemaType,
41
+ StatusPortSchema: () => StatusPortSchema,
42
+ defineConfigNode: () => defineConfigNode,
43
+ defineIONode: () => defineIONode,
44
+ defineModule: () => defineModule,
45
+ defineSchema: () => defineSchema,
46
+ registerType: () => registerType,
47
+ registerTypes: () => registerTypes
48
+ });
49
+ module.exports = __toCommonJS(index_exports);
50
+
51
+ // src/core/errors.ts
52
+ var NrgError = class _NrgError extends Error {
53
+ constructor(message) {
54
+ super(message);
55
+ this.name = "NrgError";
56
+ Object.setPrototypeOf(this, _NrgError.prototype);
57
+ }
58
+ };
59
+
60
+ // src/core/server/typed-input.ts
61
+ var TypedInput = class {
62
+ constructor(RED, node, input) {
63
+ this.RED = RED;
64
+ this.node = node;
65
+ this.input = input;
66
+ }
67
+ resolvers = {
68
+ // evaluateNodeProperty returns the node ID string for "node" type —
69
+ // resolve it to the actual node instance via RED.nodes.getNode,
70
+ // then surface the NRG wrapper if available.
71
+ node: (raw) => {
72
+ if (typeof raw === "string") {
73
+ const node = this.RED.nodes.getNode(raw);
74
+ return node?._node ?? node ?? raw;
75
+ }
76
+ return raw?._node ?? raw;
77
+ }
78
+ };
79
+ get type() {
80
+ return this.input.type;
81
+ }
82
+ get value() {
83
+ return this.input.value;
84
+ }
85
+ resolve(msg) {
86
+ return new Promise((resolve, reject) => {
87
+ this.RED.util.evaluateNodeProperty(
88
+ this.input.value,
89
+ this.input.type,
90
+ this.node,
91
+ msg,
92
+ (err, raw) => {
93
+ if (err) return reject(err);
94
+ const post = this.resolvers[this.input.type];
95
+ resolve(post ? post(raw) : raw);
96
+ }
97
+ );
98
+ });
99
+ }
100
+ };
101
+
102
+ // src/core/server/nodes/proxy.ts
103
+ function setupConfigProxy(opts) {
104
+ const { RED, node, config, schema } = opts;
105
+ const SKIP_PROPS = /* @__PURE__ */ new Set(["id", "_id", "_users"]);
106
+ const nodeRefProps = /* @__PURE__ */ new Set();
107
+ const typedInputProps = /* @__PURE__ */ new Set();
108
+ if (schema?.properties) {
109
+ for (const [key, propSchema] of Object.entries(schema.properties)) {
110
+ const s = propSchema;
111
+ if (s?.["x-nrg-node-type"]) nodeRefProps.add(key);
112
+ if (s?.["x-nrg-typed-input"]) typedInputProps.add(key);
113
+ }
114
+ }
115
+ const cache = /* @__PURE__ */ new WeakMap();
116
+ const createProxy = (obj) => {
117
+ const cached = cache.get(obj);
118
+ if (cached) return cached;
119
+ if (Array.isArray(obj)) {
120
+ const mapped = obj.map(
121
+ (item) => item && typeof item === "object" ? createProxy(item) : item
122
+ );
123
+ cache.set(obj, mapped);
124
+ return mapped;
125
+ }
126
+ const proxy = new Proxy(obj, {
127
+ get(target, prop) {
128
+ if (typeof prop === "symbol") return target[prop];
129
+ if (SKIP_PROPS.has(prop)) return target[prop];
130
+ const value = target[prop];
131
+ if (typeof value === "string" && value.length > 0 && nodeRefProps.has(prop)) {
132
+ return RED.nodes.getNode(value)?._node ?? value;
133
+ }
134
+ if (typedInputProps.has(prop) && value && typeof value === "object" && "type" in value && "value" in value) {
135
+ let ref = cache.get(value);
136
+ if (!ref) {
137
+ ref = new TypedInput(RED, node, value);
138
+ cache.set(value, ref);
139
+ }
140
+ return ref;
141
+ }
142
+ if (value && typeof value === "object") {
143
+ return createProxy(value);
144
+ }
145
+ return value;
146
+ },
147
+ set(_target, prop) {
148
+ throw new NrgError(
149
+ `Cannot set property '${String(prop)}' on read-only node config`
150
+ );
151
+ }
152
+ });
153
+ cache.set(obj, proxy);
154
+ return proxy;
155
+ };
156
+ return createProxy(config);
157
+ }
158
+
159
+ // src/core/server/utils.ts
160
+ function getCredentialsFromSchema(schema) {
161
+ const result = {};
162
+ for (const [key, value] of Object.entries(schema.properties)) {
163
+ const property = value;
164
+ result[key] = {
165
+ // NOTE: required is always false because it is controlled by the JSON Schema and AJV validation instead of using node-red client core
166
+ required: false,
167
+ type: property.format === "password" ? "password" : "text",
168
+ value: property.default ?? void 0
169
+ };
170
+ }
171
+ return result;
172
+ }
173
+
174
+ // src/core/server/nodes/symbols.ts
175
+ var WIRE_HANDLERS = Symbol.for("nrg.wireHandlers");
176
+
177
+ // src/core/server/nodes/node.ts
178
+ var cachedSettingsMap = /* @__PURE__ */ new WeakMap();
179
+ var Node = class _Node {
180
+ static type;
181
+ static category;
182
+ static configSchema;
183
+ static credentialsSchema;
184
+ static settingsSchema;
185
+ static validateSettings(RED) {
186
+ if (!this.settingsSchema) return;
187
+ RED.log.info("Validating settings");
188
+ const prefix = this.type.replace(/-./g, (x) => x[1].toUpperCase());
189
+ const properties = this.settingsSchema.properties;
190
+ const settings = {};
191
+ for (const key of Object.keys(properties)) {
192
+ const settingKey = prefix + key.charAt(0).toUpperCase() + key.slice(1);
193
+ const value = RED.settings[settingKey];
194
+ if (value !== void 0) {
195
+ settings[key] = value;
196
+ }
197
+ }
198
+ for (const [key, prop] of Object.entries(properties)) {
199
+ if (settings[key] === void 0) {
200
+ const defaultValue = prop.default ?? prop._default;
201
+ if (defaultValue !== void 0) {
202
+ settings[key] = defaultValue;
203
+ }
204
+ }
205
+ }
206
+ RED.validator.validate(settings, this.settingsSchema, {
207
+ cacheKey: this.settingsSchema.$id || `${this.type}:settings`,
208
+ throwOnError: true
209
+ });
210
+ cachedSettingsMap.set(this, settings);
211
+ RED.log.info("Settings are valid");
212
+ }
213
+ static #buildSettings(NC) {
214
+ if (!NC.settingsSchema) return;
215
+ const settings = {};
216
+ const prefix = NC.type.replace(/-./g, (x) => x[1].toUpperCase());
217
+ for (const [key, prop] of Object.entries(NC.settingsSchema.properties)) {
218
+ const settingKey = prefix + key.charAt(0).toUpperCase() + key.slice(1);
219
+ settings[settingKey] = {
220
+ value: prop.default,
221
+ exportable: prop.exportable ?? false
222
+ };
223
+ }
224
+ return settings;
225
+ }
226
+ /**
227
+ * Registers this node class with Node-RED. Handles instance creation,
228
+ * event handler wiring, settings validation, and the user's registered() hook.
229
+ */
230
+ static async register(RED) {
231
+ const NodeClass = this;
232
+ if (NodeClass.color && !/^#[0-9A-Fa-f]{6}$/.test(NodeClass.color)) {
233
+ throw new NrgError(
234
+ `Invalid color for ${NodeClass.type}: ${NodeClass.color} color must be in hex format`
235
+ );
236
+ }
237
+ RED.nodes.registerType(
238
+ NodeClass.type,
239
+ function(config) {
240
+ RED.nodes.createNode(this, config);
241
+ const node = new NodeClass(RED, this, config, this.credentials);
242
+ Object.defineProperty(this, "_node", {
243
+ value: node,
244
+ writable: false,
245
+ configurable: false,
246
+ enumerable: false
247
+ });
248
+ const createdPromise = Promise.resolve(node.created?.()).catch(
249
+ (error) => {
250
+ const message = error instanceof Error ? error.message : String(error);
251
+ this.error("Error during created hook: " + message);
252
+ throw error;
253
+ }
254
+ );
255
+ createdPromise.catch(() => {
256
+ });
257
+ node[WIRE_HANDLERS](this, createdPromise);
258
+ },
259
+ {
260
+ credentials: NodeClass.credentialsSchema ? getCredentialsFromSchema(NodeClass.credentialsSchema) : {},
261
+ settings: _Node.#buildSettings(this)
262
+ }
263
+ );
264
+ NodeClass.validateSettings(RED);
265
+ try {
266
+ await Promise.resolve(NodeClass.registered?.(RED));
267
+ } catch (error) {
268
+ const message = error instanceof Error ? error.message : String(error);
269
+ RED.log.error(
270
+ `Error during registered hook for ${NodeClass.type}: ${message}`
271
+ );
272
+ }
273
+ }
274
+ RED;
275
+ node;
276
+ context;
277
+ config;
278
+ timers = /* @__PURE__ */ new Set();
279
+ intervals = /* @__PURE__ */ new Set();
280
+ constructor(RED, node, config, credentials) {
281
+ this.RED = RED;
282
+ this.node = node;
283
+ const constructor = this.constructor;
284
+ if (constructor.configSchema) {
285
+ this.log("Validating configs");
286
+ const configResult = this.RED.validator.validate(
287
+ config,
288
+ constructor.configSchema,
289
+ {
290
+ cacheKey: constructor.configSchema.$id || `${constructor.type}:configs-schema`,
291
+ throwOnError: false
292
+ }
293
+ );
294
+ if (!configResult.valid && configResult.errors?.length) {
295
+ this.warn(
296
+ `Config validation errors: ${configResult.errors.map((e) => `${e.instancePath} ${e.message}`).join("; ")}`
297
+ );
298
+ }
299
+ }
300
+ this.config = setupConfigProxy({
301
+ RED,
302
+ node,
303
+ config,
304
+ schema: constructor.configSchema
305
+ });
306
+ if (constructor.credentialsSchema && credentials) {
307
+ this.log("Validating credentials");
308
+ const credResult = this.RED.validator.validate(
309
+ credentials,
310
+ constructor.credentialsSchema,
311
+ {
312
+ cacheKey: constructor.credentialsSchema.$id || `${constructor.type}:credentials-schema`,
313
+ throwOnError: false
314
+ }
315
+ );
316
+ if (!credResult.valid && credResult.errors?.length) {
317
+ this.warn(
318
+ `Credentials validation errors: ${credResult.errors.map((e) => `${e.instancePath} ${e.message}`).join("; ")}`
319
+ );
320
+ }
321
+ }
322
+ }
323
+ [WIRE_HANDLERS](nodeRedNode, createdPromise) {
324
+ nodeRedNode.on(
325
+ "close",
326
+ async (removed, done) => {
327
+ try {
328
+ this.log("Calling closed");
329
+ await this.#closed(removed);
330
+ this.log("Node was closed");
331
+ done();
332
+ } catch (error) {
333
+ if (error instanceof Error) {
334
+ this.error("Error while closing node: " + error.message);
335
+ done(error);
336
+ } else {
337
+ this.error("Unknown error occurred while closing node");
338
+ done(new Error("Unknown error occurred while closing node"));
339
+ }
340
+ }
341
+ }
342
+ );
343
+ }
344
+ async #closed(removed) {
345
+ try {
346
+ await Promise.resolve(this.closed?.(removed));
347
+ } finally {
348
+ this.log("clearing timers and intervals");
349
+ this.timers.forEach((t) => clearTimeout(t));
350
+ this.intervals.forEach((i) => clearInterval(i));
351
+ this.timers.clear();
352
+ this.intervals.clear();
353
+ this.log("timers and intervals cleared");
354
+ }
355
+ }
356
+ i18n(key, substitutions) {
357
+ const nodeType = this.constructor.type;
358
+ return this.RED._(`${nodeType}.${key}`, substitutions);
359
+ }
360
+ setTimeout(fn, ms) {
361
+ const timer = setTimeout(() => {
362
+ this.timers.delete(timer);
363
+ fn();
364
+ }, ms);
365
+ this.timers.add(timer);
366
+ return timer;
367
+ }
368
+ setInterval(fn, ms) {
369
+ const interval = setInterval(fn, ms);
370
+ this.intervals.add(interval);
371
+ return interval;
372
+ }
373
+ clearTimeout(timer) {
374
+ clearTimeout(timer);
375
+ this.timers.delete(timer);
376
+ }
377
+ clearInterval(interval) {
378
+ clearInterval(interval);
379
+ this.intervals.delete(interval);
380
+ }
381
+ on(event, callback) {
382
+ this.node.on(event, callback);
383
+ }
384
+ log(msg) {
385
+ this.node.log(msg);
386
+ }
387
+ warn(message) {
388
+ this.node.warn(message);
389
+ }
390
+ error(message, msg) {
391
+ this.node.error(message, msg);
392
+ }
393
+ get id() {
394
+ return this.node.id;
395
+ }
396
+ get name() {
397
+ return this.node.name;
398
+ }
399
+ get z() {
400
+ return this.node.z;
401
+ }
402
+ get credentials() {
403
+ return this.node.credentials;
404
+ }
405
+ get settings() {
406
+ const constructor = this.constructor;
407
+ return cachedSettingsMap.get(constructor) ?? {};
408
+ }
409
+ };
410
+
411
+ // src/core/server/nodes/io-node.ts
412
+ var import_typebox = require("@sinclair/typebox");
413
+
414
+ // src/core/server/nodes/context.ts
415
+ var updateLocks = /* @__PURE__ */ new WeakMap();
416
+ function setupContext(context, store) {
417
+ const get = (key) => new Promise(
418
+ (resolve, reject) => context.get(
419
+ key,
420
+ store,
421
+ (error, value) => error ? reject(error) : resolve(value)
422
+ )
423
+ );
424
+ const set = (key, value) => new Promise(
425
+ (resolve, reject) => context.set(
426
+ key,
427
+ value,
428
+ store,
429
+ (error) => error ? reject(error) : resolve()
430
+ )
431
+ );
432
+ const keys = () => new Promise(
433
+ (resolve, reject) => context.keys(store, (error, k) => error ? reject(error) : resolve(k))
434
+ );
435
+ const nativeUpdate = context.update;
436
+ const nativeIncrement = context.increment;
437
+ const update = (key, fn) => {
438
+ if (nativeUpdate) {
439
+ return new Promise(
440
+ (resolve, reject) => nativeUpdate(
441
+ key,
442
+ fn,
443
+ store,
444
+ (error, value) => error ? reject(error) : resolve(value)
445
+ )
446
+ );
447
+ }
448
+ let chains = updateLocks.get(context);
449
+ if (!chains) updateLocks.set(context, chains = /* @__PURE__ */ new Map());
450
+ const lockKey = JSON.stringify([store ?? null, key]);
451
+ const task = async () => {
452
+ const next = await fn(await get(key));
453
+ await set(key, next);
454
+ return next;
455
+ };
456
+ const run = (chains.get(lockKey) ?? Promise.resolve()).then(task, task);
457
+ chains.set(
458
+ lockKey,
459
+ run.then(
460
+ () => void 0,
461
+ () => void 0
462
+ )
463
+ );
464
+ return run;
465
+ };
466
+ const increment = (key, by = 1) => {
467
+ if (nativeIncrement) {
468
+ return new Promise(
469
+ (resolve, reject) => nativeIncrement(
470
+ key,
471
+ by,
472
+ store,
473
+ (error, value) => error ? reject(error) : resolve(value)
474
+ )
475
+ );
476
+ }
477
+ return update(
478
+ key,
479
+ (current) => typeof current === "number" ? current + by : by
480
+ );
481
+ };
482
+ return { get, set, keys, update, increment };
483
+ }
484
+
485
+ // src/core/server/nodes/io-node.ts
486
+ var import_node_async_hooks = require("node:async_hooks");
487
+ function isSchemaLike(obj) {
488
+ return obj != null && typeof obj === "object" && import_typebox.Kind in obj;
489
+ }
490
+ var RETURN_PROPERTY_PATTERN = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
491
+ var INPUT_KEY = "input";
492
+ var IONode = class _IONode extends Node {
493
+ static align;
494
+ static color;
495
+ static inputSchema;
496
+ // outputsSchema accepts any schema shape: the raw sent value (per port) is
497
+ // validated, and results are frequently non-objects.
498
+ static outputsSchema;
499
+ static validateInput = false;
500
+ static validateOutput = false;
501
+ static get inputs() {
502
+ return this.inputSchema ? 1 : 0;
503
+ }
504
+ static get outputs() {
505
+ const s = this.outputsSchema;
506
+ if (!s) return 0;
507
+ if (Array.isArray(s)) return s.length;
508
+ if (isSchemaLike(s)) return 1;
509
+ const keys = Object.keys(s);
510
+ for (const key of keys) {
511
+ if (/^\d+$/.test(key)) {
512
+ throw new NrgError(
513
+ `outputsSchema record key "${key}" in ${this.type} looks numeric. Use descriptive string names (e.g. "success", "failure") to avoid JavaScript object key ordering issues.`
514
+ );
515
+ }
516
+ if (key === "error" || key === "complete" || key === "status") {
517
+ throw new NrgError(
518
+ `outputsSchema record key "${key}" in ${this.type} is reserved for built-in ports. Use a different name (e.g. "failed" instead of "error").`
519
+ );
520
+ }
521
+ }
522
+ return keys.length;
523
+ }
524
+ /**
525
+ * The names of the base output ports when `outputsSchema` is a record of
526
+ * named ports (`{ success, failure }`), in declaration order — otherwise
527
+ * `undefined` (a single schema or a positional array). Resolved here, where
528
+ * TypeBox's `Kind` symbol is intact, so the editor reads the names directly
529
+ * instead of guessing them from a serialized (symbol-stripped) schema.
530
+ */
531
+ static get outputPortNames() {
532
+ const s = this.outputsSchema;
533
+ if (!s || Array.isArray(s) || isSchemaLike(s)) return void 0;
534
+ return Object.keys(s);
535
+ }
536
+ /**
537
+ * Per-`input()`-invocation context, scoped via AsyncLocalStorage. One store
538
+ * per class, shared by every instance: each `.run()` isolates one input()
539
+ * call (and everything it `await`s, including detached `.then`/timer
540
+ * continuations it schedules) into its own session, so concurrent inputs on a
541
+ * node never clobber each other's context and a deferred send keeps the
542
+ * context of the input that scheduled it. Real Node-RED never awaits an async
543
+ * input handler before delivering the next message, so two inputs can be in
544
+ * flight at once. `getStore()` is `undefined` only for a send made entirely
545
+ * outside any `input()` (e.g. a timer set up in `created()`): it carries no
546
+ * inherited context and delivers via `node.send`. Server-only — this is part
547
+ * of the node runtime and is never imported in a browser.
548
+ */
549
+ static #invocation = new import_node_async_hooks.AsyncLocalStorage();
550
+ context;
551
+ constructor(RED, node, config, credentials) {
552
+ super(RED, node, config, credentials);
553
+ const context = node.context();
554
+ const resolve = (scope, store) => {
555
+ const target = scope === "global" ? context.global : scope === "flow" ? context.flow : context;
556
+ return setupContext(target, store);
557
+ };
558
+ this.context = Object.assign(resolve, {
559
+ node: setupContext(context),
560
+ flow: setupContext(context.flow),
561
+ global: setupContext(context.global)
562
+ });
563
+ const outputReturnProperties = this.config.outputReturnProperties;
564
+ if (outputReturnProperties) {
565
+ for (const [port, key] of Object.entries(outputReturnProperties)) {
566
+ if (typeof key === "string" && key.trim() && !RETURN_PROPERTY_PATTERN.test(key.trim())) {
567
+ throw new NrgError(
568
+ `Invalid return property "${key}" for output port ${port} in ${this.constructor.type} \u2014 it must be a valid JavaScript identifier (letters, digits, _, $; not starting with a digit)`
569
+ );
570
+ }
571
+ }
572
+ }
573
+ }
574
+ [WIRE_HANDLERS](nodeRedNode, createdPromise) {
575
+ super[WIRE_HANDLERS](nodeRedNode, createdPromise);
576
+ const NC = this.constructor;
577
+ nodeRedNode.on(
578
+ "input",
579
+ async (msg, send, done) => {
580
+ try {
581
+ await createdPromise;
582
+ } catch {
583
+ done(new Error("Node failed to initialize"));
584
+ return;
585
+ }
586
+ try {
587
+ nodeRedNode.log("Calling input");
588
+ const result = await this.#input(msg, send);
589
+ this.#sendToPort("complete", {
590
+ ...msg,
591
+ ...result !== void 0 ? { output: result } : {},
592
+ complete: {
593
+ source: this.#nodeSource()
594
+ },
595
+ [INPUT_KEY]: msg
596
+ });
597
+ done();
598
+ nodeRedNode.log("Input processed");
599
+ } catch (error) {
600
+ const errorMsg = error instanceof Error ? error.message : "Unknown error during input handling";
601
+ const errorData = error && typeof error === "object" ? { ...error } : {};
602
+ this.#sendToPort("error", {
603
+ ...msg,
604
+ error: {
605
+ ...errorData,
606
+ name: error?.name ?? "Error",
607
+ message: errorMsg,
608
+ source: this.#nodeSource()
609
+ },
610
+ [INPUT_KEY]: msg
611
+ });
612
+ if (error instanceof Error) {
613
+ nodeRedNode.error(
614
+ "Error while processing input: " + error.message,
615
+ msg
616
+ );
617
+ done(error);
618
+ } else {
619
+ nodeRedNode.error(
620
+ "Unknown error occurred during input handling",
621
+ msg
622
+ );
623
+ done(new Error(errorMsg));
624
+ }
625
+ }
626
+ }
627
+ );
628
+ }
629
+ input(msg) {
630
+ return void 0;
631
+ }
632
+ async #input(msg, send) {
633
+ const NodeClass = this.constructor;
634
+ const shouldValidateInput = this.config.validateInput ?? NodeClass.validateInput;
635
+ if (shouldValidateInput && NodeClass.inputSchema) {
636
+ this.log("Validating input");
637
+ this.RED.validator.validate(msg, NodeClass.inputSchema, {
638
+ cacheKey: NodeClass.inputSchema.$id || `${NodeClass.type}:input-schema`,
639
+ throwOnError: true
640
+ });
641
+ this.log("Input is valid");
642
+ }
643
+ return await _IONode.#invocation.run(
644
+ { inputMsg: msg, send },
645
+ () => Promise.resolve(this.input(msg))
646
+ );
647
+ }
648
+ send(msg) {
649
+ const multi = this.baseOutputs > 1 && Array.isArray(msg);
650
+ const values = multi ? msg.slice(0, this.baseOutputs) : [msg];
651
+ const out = values.map((m, port) => {
652
+ if (m == null) return m;
653
+ this.#validatePort(m, port);
654
+ return this.#wrapOutgoing(m, this.#resolveContextMode(port), port);
655
+ });
656
+ this.#deliver(out);
657
+ }
658
+ #deliver(out) {
659
+ const send = _IONode.#invocation.getStore()?.send;
660
+ if (send) {
661
+ send(out);
662
+ } else {
663
+ this.node.send(out);
664
+ }
665
+ }
666
+ /**
667
+ * Per-port output validation. A port validates when its flow-author flag
668
+ * (`config.validateOutputs[port]`) — or the node's static `validateOutput`
669
+ * fallback — is on and a schema exists for that port.
670
+ */
671
+ #validatePort(value, port) {
672
+ const NodeClass = this.constructor;
673
+ const configured = this.config.validateOutputs?.[port];
674
+ if (!(configured ?? NodeClass.validateOutput)) return;
675
+ const schema = this.#outputSchemaForPort(port);
676
+ if (!schema) return;
677
+ this.log("Validating output");
678
+ this.RED.validator.validate(value, schema, {
679
+ cacheKey: schema.$id || `${NodeClass.type}:output-schema:${port}`,
680
+ throwOnError: true
681
+ });
682
+ this.log("Output is valid");
683
+ }
684
+ /** Resolves the output schema for a base-output port: array → `[port]`,
685
+ * record → the port-th value, single schema → itself. */
686
+ #outputSchemaForPort(port) {
687
+ const raw = this.constructor.outputsSchema;
688
+ if (!raw) return void 0;
689
+ if (Array.isArray(raw)) return raw[port];
690
+ if (isSchemaLike(raw)) return raw;
691
+ return Object.values(raw)[port];
692
+ }
693
+ /**
694
+ * The return key for an output port — `"output"` unless a custom one is set
695
+ * via `outputReturnProperties[port]` (author default and/or flow-author
696
+ * override, only possible when the node declares `outputReturnProperties`).
697
+ * `this.send(x)` always means "x is the value at this port's return key",
698
+ * never "x is the whole outgoing message".
699
+ */
700
+ #returnPropertyKey(port) {
701
+ const configured = this.config.outputReturnProperties?.[port];
702
+ if (typeof configured === "string" && configured.trim()) {
703
+ return configured.trim();
704
+ }
705
+ return "output";
706
+ }
707
+ /**
708
+ * Resolves the context mode for a base-output port from the flow author's
709
+ * per-port config (`config.outputContextModes[port]`, written by the editor
710
+ * when the node declares `outputContextModes`), falling back to `"carry"`.
711
+ */
712
+ #resolveContextMode(port) {
713
+ return this.config.outputContextModes?.[port] ?? "carry";
714
+ }
715
+ /**
716
+ * Merges a sent value into the incoming message at the returnProperty key so
717
+ * upstream message properties propagate. A fresh base is built per call so
718
+ * multi-port sends never share an object.
719
+ */
720
+ #wrapOutgoing(value, mode, port) {
721
+ const key = this.#returnPropertyKey(port);
722
+ const input = _IONode.#invocation.getStore()?.inputMsg ?? {};
723
+ if (mode === "reset") {
724
+ return { [key]: value };
725
+ }
726
+ if (mode === "trace") {
727
+ return { ...input, [key]: value, [INPUT_KEY]: input };
728
+ }
729
+ return { ...input, [key]: value };
730
+ }
731
+ // --- Built-in port management ---
732
+ get baseOutputs() {
733
+ return this.constructor.outputs ?? 0;
734
+ }
735
+ get totalOutputs() {
736
+ let count = this.baseOutputs;
737
+ if (this.config.errorPort) count++;
738
+ if (this.config.completePort) count++;
739
+ if (this.config.statusPort) count++;
740
+ return count;
741
+ }
742
+ /**
743
+ * Send a message to a specific output port by index or name.
744
+ * Custom named ports are resolved from `outputsSchema` when it is a record.
745
+ * Numeric indices refer to the base output ports (0-based).
746
+ *
747
+ * Built-in ports (`"error"`, `"complete"`, `"status"`) are managed by the
748
+ * framework and cannot be sent to directly. Use `this.status()` for status,
749
+ * throw an error or call `this.error()` for the error port, and the complete
750
+ * port is sent automatically on successful input processing.
751
+ */
752
+ sendToPort(port, msg) {
753
+ if (port === "error" || port === "complete" || port === "status") {
754
+ throw new NrgError(
755
+ `sendToPort("${port}") is not allowed. Built-in ports are managed by the framework.`
756
+ );
757
+ }
758
+ const portIndex = typeof port === "number" ? port : this.#getNamedPortIndex(port);
759
+ const mode = this.#resolveContextMode(portIndex ?? 0);
760
+ this.#sendToPort(
761
+ port,
762
+ msg == null ? msg : this.#wrapOutgoing(msg, mode, portIndex ?? 0)
763
+ );
764
+ }
765
+ #sendToPort(port, msg) {
766
+ let portIndex;
767
+ if (typeof port === "number") {
768
+ portIndex = port;
769
+ } else if (port === "error" || port === "complete" || port === "status") {
770
+ portIndex = this.#getBuiltinPortIndex(port);
771
+ if (portIndex === null) return;
772
+ } else {
773
+ portIndex = this.#getNamedPortIndex(port);
774
+ if (portIndex === null) return;
775
+ }
776
+ const out = new Array(this.totalOutputs);
777
+ out[portIndex] = msg;
778
+ this.node.send(out);
779
+ }
780
+ #getNamedPortIndex(name) {
781
+ const schema = this.constructor.outputsSchema;
782
+ if (!schema || Array.isArray(schema) || isSchemaLike(schema)) return null;
783
+ const idx = Object.keys(schema).indexOf(name);
784
+ return idx === -1 ? null : idx;
785
+ }
786
+ #getBuiltinPortIndex(name) {
787
+ if (name === "error") {
788
+ return this.config.errorPort ? this.baseOutputs : null;
789
+ }
790
+ let idx = this.baseOutputs;
791
+ if (this.config.errorPort) idx++;
792
+ if (name === "complete") {
793
+ return this.config.completePort ? idx : null;
794
+ }
795
+ if (this.config.completePort) idx++;
796
+ return this.config.statusPort ? idx : null;
797
+ }
798
+ #nodeSource() {
799
+ return {
800
+ id: this.id,
801
+ type: this.constructor.type,
802
+ name: this.name
803
+ };
804
+ }
805
+ status(status) {
806
+ this.node.status(status);
807
+ this.#sendToPort("status", {
808
+ status,
809
+ source: this.#nodeSource()
810
+ });
811
+ }
812
+ error(message, msg) {
813
+ super.error(message, msg);
814
+ if (msg) {
815
+ this.#sendToPort("error", {
816
+ ...msg,
817
+ error: {
818
+ message,
819
+ source: this.#nodeSource()
820
+ },
821
+ [INPUT_KEY]: msg
822
+ });
823
+ }
824
+ }
825
+ updateWires(wires) {
826
+ this.node.updateWires(wires);
827
+ }
828
+ receive(msg) {
829
+ this.node.receive(msg);
830
+ }
831
+ get x() {
832
+ return this.node.x;
833
+ }
834
+ get y() {
835
+ return this.node.y;
836
+ }
837
+ get g() {
838
+ return this.node.g;
839
+ }
840
+ get wires() {
841
+ return this.node.wires;
842
+ }
843
+ get credentials() {
844
+ return this.node.credentials;
845
+ }
846
+ };
847
+
848
+ // src/core/server/nodes/config-node.ts
849
+ var ConfigNode = class extends Node {
850
+ static category = "config";
851
+ context;
852
+ constructor(RED, node, config, credentials) {
853
+ super(RED, node, config, credentials);
854
+ const context = node.context();
855
+ const resolve = (scope, store) => {
856
+ const target = scope === "global" ? context.global : context;
857
+ return setupContext(target, store);
858
+ };
859
+ this.context = Object.assign(resolve, {
860
+ node: setupContext(context),
861
+ global: setupContext(context.global)
862
+ });
863
+ }
864
+ get userIds() {
865
+ return this.config._users;
866
+ }
867
+ get users() {
868
+ return this.userIds.map((id) => this.RED.nodes.getNode(id)?._node).filter((node) => node != null);
869
+ }
870
+ getUser(index) {
871
+ const id = this.userIds[index];
872
+ if (!id) return void 0;
873
+ return this.RED.nodes.getNode(id)?._node;
874
+ }
875
+ get credentials() {
876
+ return this.node.credentials;
877
+ }
878
+ };
879
+
880
+ // src/core/server/nodes/factories.ts
881
+ function defineIONode(def) {
882
+ const NodeClass = class extends IONode {
883
+ static type = def.type;
884
+ static category = def.category ?? "function";
885
+ static color = def.color ?? "#a6bbcf";
886
+ static align = def.align;
887
+ static configSchema = def.configSchema;
888
+ static credentialsSchema = def.credentialsSchema;
889
+ static settingsSchema = def.settingsSchema;
890
+ static inputSchema = def.inputSchema;
891
+ static outputsSchema = def.outputsSchema;
892
+ static validateInput = def.validateInput ?? false;
893
+ static validateOutput = def.validateOutput ?? false;
894
+ static registered(RED) {
895
+ return def.registered?.(RED);
896
+ }
897
+ async input(msg) {
898
+ if (def.input) return def.input.call(this, msg);
899
+ }
900
+ async created() {
901
+ if (def.created) return def.created.call(this);
902
+ }
903
+ async closed(removed) {
904
+ if (def.closed) return def.closed.call(this, removed);
905
+ }
906
+ };
907
+ Object.defineProperty(NodeClass, "name", {
908
+ value: def.type.replace(
909
+ /(^|-)(\w)/g,
910
+ (_, __, c) => c.toUpperCase()
911
+ ),
912
+ configurable: true
913
+ });
914
+ return NodeClass;
915
+ }
916
+ function defineConfigNode(def) {
917
+ const NodeClass = class extends ConfigNode {
918
+ static type = def.type;
919
+ static configSchema = def.configSchema;
920
+ static credentialsSchema = def.credentialsSchema;
921
+ static settingsSchema = def.settingsSchema;
922
+ static registered(RED) {
923
+ return def.registered?.(RED);
924
+ }
925
+ async created() {
926
+ if (def.created) return def.created.call(this);
927
+ }
928
+ async closed(removed) {
929
+ if (def.closed) return def.closed.call(this, removed);
930
+ }
931
+ };
932
+ Object.defineProperty(NodeClass, "name", {
933
+ value: def.type.replace(
934
+ /(^|-)(\w)/g,
935
+ (_, __, c) => c.toUpperCase()
936
+ ),
937
+ configurable: true
938
+ });
939
+ return NodeClass;
940
+ }
941
+
942
+ // src/core/validator.ts
943
+ var import_ajv = __toESM(require("ajv"), 1);
944
+ var import_ajv_formats = __toESM(require("ajv-formats"), 1);
945
+ var import_ajv_errors = __toESM(require("ajv-errors"), 1);
946
+ var Validator = class {
947
+ ajv;
948
+ constructor(options) {
949
+ const { customKeywords, customFormats, ...ajvOptions } = options || {};
950
+ this.ajv = new import_ajv.default({
951
+ allErrors: true,
952
+ code: {
953
+ source: false
954
+ },
955
+ coerceTypes: true,
956
+ removeAdditional: false,
957
+ strict: false,
958
+ strictSchema: false,
959
+ useDefaults: true,
960
+ validateFormats: true,
961
+ // NOTE: typebox handles validation via typescript
962
+ // NOTE: if true, types that are not serializable JSON, like Function, would not work
963
+ validateSchema: false,
964
+ verbose: true,
965
+ ...ajvOptions
966
+ });
967
+ (0, import_ajv_formats.default)(this.ajv);
968
+ (0, import_ajv_errors.default)(this.ajv);
969
+ this.addCustomKeywords(customKeywords || []);
970
+ this.addCustomFormats(customFormats || {});
971
+ }
972
+ /**
973
+ * Add custom keywords to the validator
974
+ */
975
+ addCustomKeywords(keywords) {
976
+ if (!keywords) return;
977
+ keywords.forEach((keyword) => {
978
+ this.ajv.addKeyword(keyword);
979
+ });
980
+ }
981
+ /**
982
+ * Add custom formats to the validator
983
+ */
984
+ addCustomFormats(formats) {
985
+ if (!formats) return;
986
+ Object.entries(formats).forEach(([name, validator]) => {
987
+ if (validator instanceof RegExp) {
988
+ this.ajv.addFormat(name, validator);
989
+ } else {
990
+ this.ajv.addFormat(name, { validate: validator });
991
+ }
992
+ });
993
+ }
994
+ /**
995
+ * Create a validator function with caching
996
+ * @param schema - JSON Schema to validate against
997
+ * @param cacheKey - Optional cache key for reusing validators
998
+ */
999
+ createValidator(schema, cacheKey) {
1000
+ if (cacheKey && !schema.$id) {
1001
+ schema.$id = cacheKey;
1002
+ }
1003
+ if (schema.$id) {
1004
+ const cached = this.ajv.getSchema(schema.$id);
1005
+ if (cached) return cached;
1006
+ }
1007
+ const validator = this.ajv.compile(schema);
1008
+ return validator;
1009
+ }
1010
+ /**
1011
+ * Validate data against a schema and return a structured result
1012
+ */
1013
+ validate(data, schema, options) {
1014
+ const validator = this.createValidator(schema, options?.cacheKey);
1015
+ const valid = validator(data);
1016
+ if (!valid) {
1017
+ const errorMessage = this.formatErrors(validator.errors);
1018
+ if (options?.throwOnError) {
1019
+ throw new ValidationError(errorMessage, validator.errors || []);
1020
+ }
1021
+ return {
1022
+ valid: false,
1023
+ errors: validator.errors || void 0,
1024
+ errorMessage
1025
+ };
1026
+ }
1027
+ return {
1028
+ valid: true,
1029
+ data
1030
+ };
1031
+ }
1032
+ /**
1033
+ * Format errors into a human-readable string
1034
+ */
1035
+ formatErrors(errors, options) {
1036
+ if (!errors || errors.length === 0) {
1037
+ return "No errors";
1038
+ }
1039
+ return this.ajv.errorsText(errors, {
1040
+ separator: "; ",
1041
+ dataVar: "data",
1042
+ ...options
1043
+ });
1044
+ }
1045
+ /**
1046
+ * Get detailed error information
1047
+ */
1048
+ getDetailedErrors(errors) {
1049
+ if (!errors || errors.length === 0) return [];
1050
+ return errors.map((error) => ({
1051
+ field: error.instancePath || "/",
1052
+ message: error.message || "Validation failed",
1053
+ keyword: error.keyword,
1054
+ params: error.params,
1055
+ schemaPath: error.schemaPath
1056
+ }));
1057
+ }
1058
+ /**
1059
+ * Add a schema to the validator for reference
1060
+ */
1061
+ addSchema(schema, key) {
1062
+ this.ajv.addSchema(schema, key);
1063
+ return this;
1064
+ }
1065
+ /**
1066
+ * Remove a schema from the validator
1067
+ */
1068
+ removeSchema(key) {
1069
+ this.ajv.removeSchema(key);
1070
+ return this;
1071
+ }
1072
+ };
1073
+ var ValidationError = class _ValidationError extends Error {
1074
+ constructor(message, errors) {
1075
+ super(message);
1076
+ this.errors = errors;
1077
+ this.name = "ValidationError";
1078
+ Object.setPrototypeOf(this, _ValidationError.prototype);
1079
+ }
1080
+ };
1081
+
1082
+ // src/core/server/validation.ts
1083
+ function initValidator(RED) {
1084
+ if (RED.validator) return;
1085
+ const nrg = {
1086
+ validator: new Validator({
1087
+ customKeywords: [
1088
+ {
1089
+ keyword: "x-nrg-skip-validation",
1090
+ schemaType: "boolean",
1091
+ valid: true
1092
+ },
1093
+ {
1094
+ keyword: "x-nrg-node-type",
1095
+ type: "string",
1096
+ validate: (schemaValue, dataValue) => {
1097
+ if (!dataValue) return true;
1098
+ const node = RED.nodes.getNode(dataValue);
1099
+ return node?.type === schemaValue;
1100
+ }
1101
+ }
1102
+ ],
1103
+ customFormats: {
1104
+ "node-id": /^[a-zA-Z0-9-_]+$/,
1105
+ "flow-id": /^[a-f0-9]{16}$/,
1106
+ "topic-path": (data) => /^[a-zA-Z0-9/_-]+$/.test(data)
1107
+ }
1108
+ })
1109
+ };
1110
+ Object.defineProperty(RED, "_nrg", {
1111
+ value: nrg,
1112
+ writable: false,
1113
+ enumerable: false,
1114
+ configurable: false
1115
+ });
1116
+ Object.defineProperty(RED, "validator", {
1117
+ get: () => nrg.validator,
1118
+ enumerable: false,
1119
+ configurable: false
1120
+ });
1121
+ }
1122
+
1123
+ // src/core/server/api/assets.ts
1124
+ var import_path = __toESM(require("path"), 1);
1125
+ var import_fs = __toESM(require("fs"), 1);
1126
+ var import_module = require("module");
1127
+ function serveFile(filePath) {
1128
+ return (_req, res, next) => {
1129
+ if (!import_fs.default.existsSync(filePath)) return next();
1130
+ res.setHeader("Content-Type", "application/javascript");
1131
+ import_fs.default.createReadStream(filePath).pipe(res);
1132
+ };
1133
+ }
1134
+ function initAssetsRoutes(router) {
1135
+ const resourcesDir = import_path.default.resolve(__dirname, "./resources");
1136
+ if (!import_fs.default.existsSync(resourcesDir)) return;
1137
+ const _require = (0, import_module.createRequire)(import_path.default.join(__dirname, "package.json"));
1138
+ const vueFile = process.env.NODE_ENV !== "production" ? _require.resolve("vue/dist/vue.esm-browser.js") : _require.resolve("vue/dist/vue.esm-browser.prod.js");
1139
+ router.get(
1140
+ "/nrg/assets/nrg-client.js",
1141
+ serveFile(import_path.default.join(resourcesDir, "nrg-client.js"))
1142
+ );
1143
+ router.get("/nrg/assets/vue.esm-browser.prod.js", serveFile(vueFile));
1144
+ router.get("/nrg/assets/vue.esm-browser.js", serveFile(vueFile));
1145
+ }
1146
+
1147
+ // src/core/server/api/routes.ts
1148
+ var _initialized = false;
1149
+ function initRoutes(RED) {
1150
+ if (_initialized) return;
1151
+ _initialized = true;
1152
+ initAssetsRoutes(RED.httpAdmin);
1153
+ }
1154
+
1155
+ // src/core/server/registration.ts
1156
+ async function registerType(RED, NodeClass) {
1157
+ RED.log.debug(`Registering Type: ${NodeClass.type}`);
1158
+ if (!(NodeClass.prototype instanceof Node)) {
1159
+ throw new NrgError(
1160
+ `${NodeClass.name} must extend IONode or ConfigNode classes`
1161
+ );
1162
+ }
1163
+ if (!NodeClass.type) {
1164
+ throw new NrgError("type must be provided when registering the node");
1165
+ }
1166
+ await NodeClass.register(RED);
1167
+ RED.log.debug(`Type registered: ${NodeClass.type}`);
1168
+ }
1169
+ function registerTypes(nodes) {
1170
+ const fn = Object.assign(
1171
+ async function(RED) {
1172
+ initValidator(RED);
1173
+ initRoutes(RED);
1174
+ try {
1175
+ RED.log.info("Registering node types in series");
1176
+ for (const NodeClass of nodes) {
1177
+ await registerType(RED, NodeClass);
1178
+ }
1179
+ RED.log.info("All node types registered in series");
1180
+ } catch (error) {
1181
+ RED.log.error("Error registering node types:", error);
1182
+ throw error;
1183
+ }
1184
+ },
1185
+ { nodes }
1186
+ );
1187
+ return fn;
1188
+ }
1189
+
1190
+ // src/core/constants.ts
1191
+ var TYPED_INPUT_TYPES = [
1192
+ "msg",
1193
+ "flow",
1194
+ "global",
1195
+ "str",
1196
+ "num",
1197
+ "bool",
1198
+ "json",
1199
+ "bin",
1200
+ "re",
1201
+ "jsonata",
1202
+ "date",
1203
+ "env",
1204
+ "node",
1205
+ "cred"
1206
+ ];
1207
+
1208
+ // src/core/server/schemas/type.ts
1209
+ var import_typebox2 = require("@sinclair/typebox");
1210
+ var import_rules = require("ajv/dist/compile/rules");
1211
+ function NodeRef(nodeClass, options) {
1212
+ return {
1213
+ ...import_typebox2.Type.String({
1214
+ description: options?.description || `Reference to ${nodeClass.type}`,
1215
+ format: "node-id"
1216
+ }),
1217
+ "x-nrg-node-type": nodeClass.type,
1218
+ ...options,
1219
+ [import_typebox2.Kind]: "NodeRef"
1220
+ };
1221
+ }
1222
+ function TypedInput2(options) {
1223
+ return {
1224
+ ...TypedInputSchema,
1225
+ "x-nrg-typed-input": true,
1226
+ ...options,
1227
+ [import_typebox2.Kind]: "TypedInput"
1228
+ };
1229
+ }
1230
+ function NrgString(options) {
1231
+ return import_typebox2.Type.String(options);
1232
+ }
1233
+ function OutputReturnProperties(options) {
1234
+ return import_typebox2.Type.Record(
1235
+ import_typebox2.Type.Number(),
1236
+ import_typebox2.Type.String({ pattern: "^[A-Za-z_$][A-Za-z0-9_$]*$" }),
1237
+ {
1238
+ description: "Per-port return property, keyed by output port index. A missing entry falls back to `output`.",
1239
+ default: {},
1240
+ ...options
1241
+ }
1242
+ );
1243
+ }
1244
+ function OutputContextModes(options) {
1245
+ return import_typebox2.Type.Record(
1246
+ import_typebox2.Type.Number(),
1247
+ import_typebox2.Type.Union([
1248
+ import_typebox2.Type.Literal("carry"),
1249
+ import_typebox2.Type.Literal("trace"),
1250
+ import_typebox2.Type.Literal("reset")
1251
+ ]),
1252
+ {
1253
+ description: "Per-port context mode, keyed by output port index. A missing entry falls back to `carry`.",
1254
+ default: {},
1255
+ ...options
1256
+ }
1257
+ );
1258
+ }
1259
+ var SchemaType = Object.assign({}, import_typebox2.Type, {
1260
+ String: NrgString,
1261
+ NodeRef,
1262
+ TypedInput: TypedInput2,
1263
+ OutputReturnProperties,
1264
+ OutputContextModes
1265
+ });
1266
+ function markNonValidatable(schema) {
1267
+ const type = schema.type;
1268
+ const hasInvalidType = type !== void 0 && (Array.isArray(type) ? !type.every(import_rules.isJSONType) : !(0, import_rules.isJSONType)(type));
1269
+ if (hasInvalidType) {
1270
+ schema["x-nrg-skip-validation"] = true;
1271
+ if (schema.default !== void 0) {
1272
+ schema._default = schema.default;
1273
+ delete schema.default;
1274
+ }
1275
+ delete schema.type;
1276
+ }
1277
+ if (schema.properties) {
1278
+ for (const prop of Object.values(schema.properties)) {
1279
+ markNonValidatable(prop);
1280
+ }
1281
+ }
1282
+ if (schema.items) {
1283
+ markNonValidatable(schema.items);
1284
+ }
1285
+ if (schema.anyOf) {
1286
+ schema.anyOf.forEach((s) => markNonValidatable(s));
1287
+ }
1288
+ if (schema.allOf) {
1289
+ schema.allOf.forEach((s) => markNonValidatable(s));
1290
+ }
1291
+ if (schema.oneOf) {
1292
+ schema.oneOf.forEach((s) => markNonValidatable(s));
1293
+ }
1294
+ return schema;
1295
+ }
1296
+ function defineSchema(properties, options) {
1297
+ const schema = SchemaType.Object(properties, options);
1298
+ return markNonValidatable(schema);
1299
+ }
1300
+
1301
+ // src/core/server/schemas/base.ts
1302
+ var NodeConfigSchema = SchemaType.Object({
1303
+ id: SchemaType.String(),
1304
+ type: SchemaType.String(),
1305
+ name: SchemaType.String(),
1306
+ z: SchemaType.Optional(SchemaType.String())
1307
+ });
1308
+ var ConfigNodeConfigSchema = SchemaType.Object({
1309
+ ...NodeConfigSchema.properties,
1310
+ _users: SchemaType.Array(SchemaType.String())
1311
+ });
1312
+ var IONodeConfigSchema = SchemaType.Object({
1313
+ ...NodeConfigSchema.properties,
1314
+ wires: SchemaType.Array(
1315
+ SchemaType.Array(SchemaType.String(), { default: [] }),
1316
+ {
1317
+ default: [[]]
1318
+ }
1319
+ ),
1320
+ x: SchemaType.Number(),
1321
+ y: SchemaType.Number(),
1322
+ g: SchemaType.Optional(SchemaType.String())
1323
+ });
1324
+ var TypedInputSchema = SchemaType.Object(
1325
+ {
1326
+ value: SchemaType.Union(
1327
+ [
1328
+ SchemaType.String(),
1329
+ SchemaType.Number(),
1330
+ SchemaType.Boolean(),
1331
+ SchemaType.Null()
1332
+ ],
1333
+ {
1334
+ description: "The actual value entered or selected.",
1335
+ default: ""
1336
+ }
1337
+ ),
1338
+ type: SchemaType.Union(
1339
+ TYPED_INPUT_TYPES.map((type) => SchemaType.Literal(type)),
1340
+ {
1341
+ description: "The type of the value (string, number, message property, etc.)",
1342
+ default: "str"
1343
+ }
1344
+ )
1345
+ },
1346
+ {
1347
+ description: "Represents a Node-RED TypedInput value and its type.",
1348
+ default: {
1349
+ type: "str",
1350
+ value: ""
1351
+ }
1352
+ }
1353
+ );
1354
+ var NodeSourceSchema = SchemaType.Object({
1355
+ id: SchemaType.String(),
1356
+ type: SchemaType.String(),
1357
+ name: SchemaType.String()
1358
+ });
1359
+ var ErrorPortSchema = SchemaType.Object({
1360
+ error: SchemaType.Object({
1361
+ message: SchemaType.String(),
1362
+ source: NodeSourceSchema
1363
+ })
1364
+ });
1365
+ var CompletePortSchema = SchemaType.Object({
1366
+ complete: SchemaType.Object({
1367
+ source: NodeSourceSchema
1368
+ })
1369
+ });
1370
+ var StatusPortSchema = SchemaType.Object({
1371
+ status: SchemaType.Union([
1372
+ SchemaType.Object({
1373
+ fill: SchemaType.Optional(
1374
+ SchemaType.Union([
1375
+ SchemaType.Literal("red"),
1376
+ SchemaType.Literal("green")
1377
+ ])
1378
+ ),
1379
+ shape: SchemaType.Optional(
1380
+ SchemaType.Union([
1381
+ SchemaType.Literal("dot"),
1382
+ SchemaType.Literal("string")
1383
+ ])
1384
+ ),
1385
+ text: SchemaType.Optional(SchemaType.String())
1386
+ }),
1387
+ SchemaType.String()
1388
+ ]),
1389
+ source: NodeSourceSchema
1390
+ });
1391
+
1392
+ // src/core/server/index.ts
1393
+ function defineModule(definition) {
1394
+ return definition;
1395
+ }
1396
+ // Annotate the CommonJS export names for ESM import in node:
1397
+ 0 && (module.exports = {
1398
+ CompletePortSchema,
1399
+ ConfigNode,
1400
+ ErrorPortSchema,
1401
+ IONode,
1402
+ Node,
1403
+ NodeSourceSchema,
1404
+ NrgError,
1405
+ SchemaType,
1406
+ StatusPortSchema,
1407
+ defineConfigNode,
1408
+ defineIONode,
1409
+ defineModule,
1410
+ defineSchema,
1411
+ registerType,
1412
+ registerTypes
1413
+ });