tina4-nodejs 3.13.92 → 3.13.94

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 (134) hide show
  1. package/CLAUDE.md +16 -3
  2. package/README.md +1 -1
  3. package/package.json +12 -9
  4. package/packages/cli/dist/bin.js +1260 -969
  5. package/packages/core/dist/index.js +1260 -969
  6. package/packages/core/src/devMailbox.ts +20 -44
  7. package/packages/core/src/index.ts +2 -2
  8. package/packages/core/src/messenger.ts +72 -0
  9. package/packages/core/src/queueBackends/kafkaBackend.ts +108 -12
  10. package/packages/core/src/sessionHandlers/childError.ts +72 -0
  11. package/packages/core/src/sessionHandlers/mongoClient.ts +9 -3
  12. package/packages/core/src/sessionHandlers/redisHandler.ts +18 -5
  13. package/packages/core/src/sessionHandlers/respClient.ts +5 -1
  14. package/packages/frond/dist/index.js +74 -31
  15. package/packages/frond/src/engine.ts +99 -33
  16. package/packages/orm/dist/index.js +3055 -2764
  17. package/packages/orm/src/adapters/sqlite.ts +4 -1
  18. package/packages/orm/src/database.ts +108 -8
  19. package/types/cli/src/bin.d.ts +92 -0
  20. package/types/cli/src/commands/build.d.ts +2 -0
  21. package/types/cli/src/commands/generate.d.ts +47 -0
  22. package/types/cli/src/commands/init.d.ts +1 -0
  23. package/types/cli/src/commands/metrics.d.ts +6 -0
  24. package/types/cli/src/commands/migrate.d.ts +1 -0
  25. package/types/cli/src/commands/migrateCreate.d.ts +1 -0
  26. package/types/cli/src/commands/migrateRollback.d.ts +1 -0
  27. package/types/cli/src/commands/migrateStatus.d.ts +1 -0
  28. package/types/cli/src/commands/queue.d.ts +20 -0
  29. package/types/cli/src/commands/routes.d.ts +1 -0
  30. package/types/cli/src/commands/seed.d.ts +1 -0
  31. package/types/cli/src/commands/serve.d.ts +6 -0
  32. package/types/cli/src/commands/test.d.ts +1 -0
  33. package/types/core/src/ai.d.ts +64 -0
  34. package/types/core/src/api.d.ts +262 -0
  35. package/types/core/src/auth.d.ts +154 -0
  36. package/types/core/src/authGate.d.ts +20 -0
  37. package/types/core/src/background.d.ts +34 -0
  38. package/types/core/src/cache.d.ts +160 -0
  39. package/types/core/src/constants.d.ts +38 -0
  40. package/types/core/src/container.d.ts +44 -0
  41. package/types/core/src/context/chunker.d.ts +31 -0
  42. package/types/core/src/context/index.d.ts +93 -0
  43. package/types/core/src/devAdmin.d.ts +179 -0
  44. package/types/core/src/devMailbox.d.ts +54 -0
  45. package/types/core/src/docs.d.ts +141 -0
  46. package/types/core/src/docsAutoDiscovery.d.ts +6 -0
  47. package/types/core/src/dotenv.d.ts +65 -0
  48. package/types/core/src/env.d.ts +28 -0
  49. package/types/core/src/errorOverlay.d.ts +36 -0
  50. package/types/core/src/events.d.ts +75 -0
  51. package/types/core/src/fakeData.d.ts +55 -0
  52. package/types/core/src/feedback.d.ts +90 -0
  53. package/types/core/src/graphql.d.ts +207 -0
  54. package/types/core/src/health.d.ts +22 -0
  55. package/types/core/src/htmlElement.d.ts +75 -0
  56. package/types/core/src/i18n.d.ts +37 -0
  57. package/types/core/src/index.d.ts +93 -0
  58. package/types/core/src/job.d.ts +39 -0
  59. package/types/core/src/logger.d.ts +123 -0
  60. package/types/core/src/mcp.d.ts +248 -0
  61. package/types/core/src/messenger.d.ts +191 -0
  62. package/types/core/src/metrics.d.ts +77 -0
  63. package/types/core/src/middleware.d.ts +207 -0
  64. package/types/core/src/mqtt.d.ts +257 -0
  65. package/types/core/src/mqttMessage.d.ts +67 -0
  66. package/types/core/src/plan.d.ts +96 -0
  67. package/types/core/src/projectIndex.d.ts +56 -0
  68. package/types/core/src/queue.d.ts +219 -0
  69. package/types/core/src/queueBackends/kafkaBackend.d.ts +117 -0
  70. package/types/core/src/queueBackends/liteBackend.d.ts +119 -0
  71. package/types/core/src/queueBackends/mongoBackend.d.ts +97 -0
  72. package/types/core/src/queueBackends/rabbitmqBackend.d.ts +55 -0
  73. package/types/core/src/rateLimiter.d.ts +49 -0
  74. package/types/core/src/request.d.ts +25 -0
  75. package/types/core/src/response.d.ts +28 -0
  76. package/types/core/src/routeDiscovery.d.ts +12 -0
  77. package/types/core/src/router.d.ts +355 -0
  78. package/types/core/src/scss.d.ts +19 -0
  79. package/types/core/src/server.d.ts +131 -0
  80. package/types/core/src/service.d.ts +115 -0
  81. package/types/core/src/session.d.ts +256 -0
  82. package/types/core/src/sessionHandlers/childError.d.ts +34 -0
  83. package/types/core/src/sessionHandlers/databaseHandler.d.ts +42 -0
  84. package/types/core/src/sessionHandlers/mongoClient.d.ts +24 -0
  85. package/types/core/src/sessionHandlers/mongoHandler.d.ts +61 -0
  86. package/types/core/src/sessionHandlers/redisHandler.d.ts +60 -0
  87. package/types/core/src/sessionHandlers/respClient.d.ts +22 -0
  88. package/types/core/src/sessionHandlers/valkeyHandler.d.ts +65 -0
  89. package/types/core/src/static.d.ts +2 -0
  90. package/types/core/src/test.d.ts +94 -0
  91. package/types/core/src/testClient.d.ts +36 -0
  92. package/types/core/src/testing.d.ts +58 -0
  93. package/types/core/src/types.d.ts +219 -0
  94. package/types/core/src/validator.d.ts +52 -0
  95. package/types/core/src/websocket.d.ts +376 -0
  96. package/types/core/src/websocketBackplane.d.ts +166 -0
  97. package/types/core/src/websocketConnection.d.ts +54 -0
  98. package/types/core/src/wsdl.d.ts +101 -0
  99. package/types/frond/src/engine.d.ts +263 -0
  100. package/types/frond/src/index.d.ts +2 -0
  101. package/types/orm/src/adapters/firebird.d.ts +138 -0
  102. package/types/orm/src/adapters/mongodb.d.ts +81 -0
  103. package/types/orm/src/adapters/mssql.d.ts +70 -0
  104. package/types/orm/src/adapters/mysql.d.ts +66 -0
  105. package/types/orm/src/adapters/odbc.d.ts +97 -0
  106. package/types/orm/src/adapters/postgres.d.ts +85 -0
  107. package/types/orm/src/adapters/sqlite.d.ts +56 -0
  108. package/types/orm/src/autoCrud.d.ts +73 -0
  109. package/types/orm/src/baseModel.d.ts +391 -0
  110. package/types/orm/src/cachedDatabase.d.ts +177 -0
  111. package/types/orm/src/database.d.ts +609 -0
  112. package/types/orm/src/databaseResult.d.ts +85 -0
  113. package/types/orm/src/docstore.d.ts +182 -0
  114. package/types/orm/src/fakeData.d.ts +22 -0
  115. package/types/orm/src/index.d.ts +40 -0
  116. package/types/orm/src/migration.d.ts +275 -0
  117. package/types/orm/src/model.d.ts +7 -0
  118. package/types/orm/src/query.d.ts +14 -0
  119. package/types/orm/src/queryBuilder.d.ts +173 -0
  120. package/types/orm/src/realtime/index.d.ts +7 -0
  121. package/types/orm/src/realtime/models/attachment.d.ts +43 -0
  122. package/types/orm/src/realtime/models/channel.d.ts +32 -0
  123. package/types/orm/src/realtime/models/channelMember.d.ts +32 -0
  124. package/types/orm/src/realtime/models/message.d.ts +36 -0
  125. package/types/orm/src/realtime/models/workspace.d.ts +26 -0
  126. package/types/orm/src/realtime/realtime.d.ts +24 -0
  127. package/types/orm/src/realtime/storage.d.ts +61 -0
  128. package/types/orm/src/seeder.d.ts +118 -0
  129. package/types/orm/src/sqlTranslator.d.ts +134 -0
  130. package/types/orm/src/types.d.ts +138 -0
  131. package/types/orm/src/validation.d.ts +6 -0
  132. package/types/swagger/src/generator.d.ts +46 -0
  133. package/types/swagger/src/index.d.ts +2 -0
  134. package/types/swagger/src/ui.d.ts +11 -0
@@ -0,0 +1,207 @@
1
+ import type { Tina4Request, Tina4Response, Middleware } from "./types.js";
2
+ export declare class MiddlewareChain {
3
+ private middlewares;
4
+ use(fn: Middleware): void;
5
+ /**
6
+ * Run the chain in REGISTRATION order — each middleware runs exactly once,
7
+ * in the order it was attached via use(). The chain advances from ONE
8
+ * source only: `next()`. (The old runner double-advanced — a for-loop index
9
+ * AND next() both incremented — so every other middleware was silently
10
+ * skipped. Fixed by driving the chain purely by next(), mirroring Python's
11
+ * _make_mw_continuation Russian-doll continuation.)
12
+ *
13
+ * A middleware may stop the chain by:
14
+ * - not calling next() (it owns the response), or
15
+ * - ending the response (res.raw.writableEnded).
16
+ * Returns true when the whole chain ran to completion (handler may proceed),
17
+ * false when it was short-circuited.
18
+ */
19
+ run(req: Tina4Request, res: Tina4Response): Promise<boolean>;
20
+ }
21
+ export declare class MiddlewareRunner {
22
+ /** Globally registered middleware classes (parity with PHP/Ruby/Python orchestrators). */
23
+ private static globalMiddleware;
24
+ /**
25
+ * Register a middleware class to run on every request.
26
+ * Mirrors Tina4\Middleware::use (PHP), Tina4::Middleware.use (Ruby),
27
+ * and Middleware.use (Python).
28
+ */
29
+ static use(cls: any): void;
30
+ /** Return the list of globally registered middleware classes. */
31
+ static getGlobal(): any[];
32
+ /** Clear all globally registered middleware (primarily for tests). */
33
+ static reset(): void;
34
+ /**
35
+ * Discover the before-prefixed / after-prefixed method names on a
36
+ * middleware class in DEFINITION order (M1).
37
+ * `Object.getOwnPropertyNames` returns a class's own
38
+ * static method names in source-declaration order — we deliberately do NOT
39
+ * sort() them, so within a class the hooks run in the order they were
40
+ * written (parity with Python walking __dict__, PHP get_class_methods, Ruby
41
+ * instance_methods(false)). Cross-class order is the natural iteration of
42
+ * the registered classes = REGISTRATION order.
43
+ */
44
+ private static methodNames;
45
+ /**
46
+ * Execute every beforeX static method found on the supplied classes.
47
+ *
48
+ * ORDER (M1): cross-class = REGISTRATION order (the order classes were
49
+ * attached via Router.use / MiddlewareRunner.use); within a class =
50
+ * DEFINITION order (source order, never alphabetical). before_* run before
51
+ * the handler.
52
+ *
53
+ * THROW (M2): each before* call is wrapped — a throwing middleware is
54
+ * LOGGED and produces a deterministic clean 500 (it never crashes the
55
+ * worker / leaks an unhandled exception), and the chain short-circuits
56
+ * (skip = true, handler skipped).
57
+ *
58
+ * Short-circuits (skip = true, handler skipped) when a before* sets a
59
+ * status >= 400 or ends/500s the response.
60
+ *
61
+ * ASYNC — each hook is awaited so middleware can perform async work (e.g.
62
+ * the distributed responseCache before-hook awaiting `backend.get`). Awaiting
63
+ * a synchronous hook that returns an array is harmless (the array resolves
64
+ * immediately), so existing sync hooks keep working unchanged.
65
+ *
66
+ * Returns [req, res, shouldContinue].
67
+ */
68
+ static runBefore(classes: any[], req: Tina4Request, res: Tina4Response): Promise<[Tina4Request, Tina4Response, boolean]>;
69
+ /**
70
+ * Execute every afterX static method found on the supplied classes.
71
+ *
72
+ * ORDER (M1): cross-class = REGISTRATION order; within a class = DEFINITION
73
+ * order. after_* run after the handler.
74
+ *
75
+ * THROW (M2): each after* call is wrapped — a throwing after middleware is
76
+ * LOGGED and produces a clean 500, then the remaining after* STILL run
77
+ * (they may add headers / logging). No unhandled exception leaks.
78
+ *
79
+ * AFTER-ON-4xx RULE (M2): after_* ALWAYS run, even when a before_*
80
+ * short-circuited with status >= 400 and the handler was skipped — so they
81
+ * can still add headers / logging. The dispatcher calls runAfter
82
+ * unconditionally after the before/handler block (see server.ts).
83
+ *
84
+ * ASYNC — each hook is awaited (e.g. the responseCache after-hook awaiting
85
+ * `backend.set`). Awaiting a synchronous hook is harmless, so existing sync
86
+ * after-hooks keep working unchanged.
87
+ */
88
+ static runAfter(classes: any[], req: Tina4Request, res: Tina4Response): Promise<[Tina4Request, Tina4Response]>;
89
+ }
90
+ /** Configuration for the CORS middleware */
91
+ export interface CorsConfig {
92
+ /** Allowed origins. Default: "*" (or TINA4_CORS_ORIGINS env, comma-separated) */
93
+ origins?: string | string[];
94
+ /** Allowed methods. Default: standard REST methods (or TINA4_CORS_METHODS env) */
95
+ methods?: string | string[];
96
+ /** Allowed headers. Default: Content-Type, Authorization (or TINA4_CORS_HEADERS env) */
97
+ headers?: string | string[];
98
+ /** Access-Control-Max-Age in seconds. Default: 86400 (or TINA4_CORS_MAX_AGE env) */
99
+ maxAge?: number;
100
+ }
101
+ /**
102
+ * Built-in CORS middleware (function form).
103
+ * Reads configuration from env vars if not provided:
104
+ * TINA4_CORS_ORIGINS — comma-separated list of allowed origins, or "*"
105
+ * TINA4_CORS_METHODS — comma-separated list of allowed methods
106
+ * TINA4_CORS_HEADERS — comma-separated list of allowed headers
107
+ * TINA4_CORS_MAX_AGE — preflight cache duration in seconds
108
+ *
109
+ * Preflight (OPTIONS) returns 204 with appropriate headers.
110
+ * Supports wildcard ("*") and specific origin matching.
111
+ */
112
+ export declare function cors(config?: CorsConfig): Middleware;
113
+ /**
114
+ * Class-based CORS middleware using the before/after convention.
115
+ * Wraps the same CORS logic as the `cors()` function middleware.
116
+ *
117
+ * Usage:
118
+ * Router.use(CorsMiddleware);
119
+ */
120
+ export declare class CorsMiddleware {
121
+ static beforeCors(req: Tina4Request, res: Tina4Response): [Tina4Request, Tina4Response];
122
+ /**
123
+ * Check if a request is an OPTIONS preflight.
124
+ */
125
+ static isPreflight(method: string): boolean;
126
+ }
127
+ /**
128
+ * Class-based rate limiter middleware using the before/after convention.
129
+ * Uses the same sliding-window algorithm as the `rateLimiter()` function.
130
+ *
131
+ * Reads configuration from env vars:
132
+ * TINA4_RATE_LIMIT — max requests per window (default 100)
133
+ * TINA4_RATE_WINDOW — window duration in seconds (default 60)
134
+ *
135
+ * Usage:
136
+ * Router.use(RateLimiterMiddleware);
137
+ */
138
+ export declare class RateLimiterMiddleware {
139
+ private static store;
140
+ private static cleanupTimer;
141
+ private static ensureCleanup;
142
+ static beforeRateLimit(req: Tina4Request, res: Tina4Response): [Tina4Request, Tina4Response];
143
+ /**
144
+ * Check if an IP is within rate limits without recording a request.
145
+ * Returns [allowed, info] matching Python/Ruby API.
146
+ */
147
+ static check(ip: string): [boolean, {
148
+ limit: number;
149
+ remaining: number;
150
+ reset: number;
151
+ window: number;
152
+ }];
153
+ }
154
+ /**
155
+ * Class-based request logger middleware using the before/after convention.
156
+ * `beforeLog` stamps the request start time.
157
+ * `afterLog` prints the coloured status line.
158
+ *
159
+ * Usage:
160
+ * Router.use(RequestLogger);
161
+ */
162
+ export declare class RequestLogger {
163
+ static beforeLog(req: Tina4Request, res: Tina4Response): [Tina4Request, Tina4Response];
164
+ static afterLog(req: Tina4Request, res: Tina4Response): [Tina4Request, Tina4Response];
165
+ }
166
+ /**
167
+ * Class-based security headers middleware using the before/after convention.
168
+ * Auto-injects security headers on every response.
169
+ *
170
+ * Configuration via env vars:
171
+ * TINA4_FRAME_OPTIONS — X-Frame-Options (default: "SAMEORIGIN")
172
+ * TINA4_HSTS — Strict-Transport-Security max-age value
173
+ * (default: "" = off; set to "31536000" to enable)
174
+ * TINA4_CSP — Content-Security-Policy (default: "default-src 'self'")
175
+ * TINA4_REFERRER_POLICY — Referrer-Policy (default: "strict-origin-when-cross-origin")
176
+ * TINA4_PERMISSIONS_POLICY — Permissions-Policy (default: "camera=(), microphone=(), geolocation=()")
177
+ *
178
+ * Usage:
179
+ * Router.use(SecurityHeadersMiddleware);
180
+ */
181
+ export declare class SecurityHeadersMiddleware {
182
+ static beforeSecurity(req: Tina4Request, res: Tina4Response): [Tina4Request, Tina4Response];
183
+ }
184
+ /**
185
+ * Class-based CSRF middleware using the before/after convention.
186
+ * Validates form tokens on state-changing requests (POST, PUT, PATCH, DELETE).
187
+ *
188
+ * Off by default — only active when TINA4_CSRF=true in .env or when
189
+ * registered explicitly via Router.use(CsrfMiddleware).
190
+ *
191
+ * Behaviour:
192
+ * - Skips GET, HEAD, OPTIONS requests.
193
+ * - Skips routes marked .noAuth().
194
+ * - Skips requests with a valid Authorization: Bearer header (API clients).
195
+ * - Checks request body formToken then X-Form-Token header.
196
+ * - Rejects if token found in query string formToken (log warning, 403).
197
+ * - Validates token with validToken using SECRET env var.
198
+ * - If token payload has session_id, verifies it matches request session.
199
+ * - Returns 403 on failure.
200
+ *
201
+ * Usage:
202
+ * Router.use(CsrfMiddleware);
203
+ */
204
+ export declare class CsrfMiddleware {
205
+ static beforeCsrf(req: Tina4Request, res: Tina4Response): [Tina4Request, Tina4Response];
206
+ }
207
+ export declare function requestLogger(): Middleware;
@@ -0,0 +1,257 @@
1
+ /**
2
+ * Zero-dependency MQTT 3.1.1 client — the protocol every broker and every IoT
3
+ * device already speaks.
4
+ *
5
+ * Built on Node's `node:net` and `node:tls` stdlib modules only: no npm package,
6
+ * so an app that talks to Mosquitto / EMQX / HiveMQ / AWS IoT adds nothing to its
7
+ * dependency tree. Shaped like the Queue on purpose — publish / subscribe /
8
+ * consume:
9
+ *
10
+ * import { Mqtt } from "@tina4stack/tina4-node";
11
+ *
12
+ * const mqtt = new Mqtt({ url: "mqtt://broker:1883" }); // TINA4_MQTT_URL
13
+ * await mqtt.connect();
14
+ * await mqtt.publish("fleet/meter-42/telemetry", '{"kwh":12.5}', 1);
15
+ *
16
+ * for await (const message of mqtt.consume("fleet/+/telemetry", 1)) {
17
+ * if (message.isDuplicate()) continue; // QoS 1 is at-least-once
18
+ * store(message.topic, message.payload);
19
+ * }
20
+ *
21
+ * Environment: TINA4_MQTT_URL (default mqtt://127.0.0.1:1883),
22
+ * TINA4_MQTT_CLIENT_ID, TINA4_MQTT_KEEPALIVE (seconds, default 60),
23
+ * TINA4_MQTT_CA_FILE, TINA4_MQTT_TLS_VERIFY.
24
+ *
25
+ * Node has no synchronous blocking socket read, so connect()/publish()/
26
+ * subscribe()/receive() are async and consume() is an async generator — the same
27
+ * idiom as the Queue. No background task runs by default; opt in to the
28
+ * cooperative keepalive with startKeepalive(), which registers a background()
29
+ * task exactly like the queue consumers do.
30
+ *
31
+ * Single reader: like every MQTT client the socket has ONE network reader. Call
32
+ * receive()/consume() from one place.
33
+ */
34
+ import { MqttMessage } from "./mqttMessage.js";
35
+ /** Any MQTT protocol / connection failure. */
36
+ export declare class MqttError extends Error {
37
+ constructor(message: string);
38
+ }
39
+ /** The broker did not answer inside the timeout. */
40
+ export declare class MqttTimeoutError extends MqttError {
41
+ constructor(message: string);
42
+ }
43
+ export interface MqttOptions {
44
+ url?: string;
45
+ clientId?: string;
46
+ username?: string;
47
+ password?: string;
48
+ caFile?: string;
49
+ tlsVerify?: boolean;
50
+ keepalive?: number;
51
+ cleanSession?: boolean;
52
+ willTopic?: string;
53
+ willPayload?: unknown;
54
+ willQos?: number;
55
+ willRetain?: boolean;
56
+ /** Seconds to wait for a control-packet answer (CONNACK / PUBACK / SUBACK). */
57
+ timeout?: number;
58
+ /** Seconds to wait for an application message; null/undefined blocks. */
59
+ readTimeout?: number | null;
60
+ }
61
+ export interface ParsedMqttUrl {
62
+ host: string;
63
+ port: number;
64
+ tls: boolean;
65
+ username: string | null;
66
+ password: string | null;
67
+ }
68
+ export declare class Mqtt {
69
+ readonly host: string;
70
+ readonly port: number;
71
+ readonly clientId: string;
72
+ readonly keepalive: number;
73
+ readonly cleanSession: boolean;
74
+ readonly username: string | null;
75
+ private readonly secure;
76
+ private readonly password;
77
+ private readonly caFile;
78
+ private readonly tlsVerify;
79
+ private readonly willTopic;
80
+ private readonly willPayload;
81
+ private readonly willQos;
82
+ private readonly willRetain;
83
+ private readonly timeout;
84
+ private readonly readTimeout;
85
+ private packetId;
86
+ private inbox;
87
+ private lastWriteAt;
88
+ private socket;
89
+ private keepaliveTask;
90
+ private readBuffer;
91
+ private waiter;
92
+ private socketError;
93
+ constructor(options?: MqttOptions);
94
+ /**
95
+ * Split an MQTT url into { host, port, tls, username, password }.
96
+ *
97
+ * "mqtt://host:port" and "tcp://host:port" are plain TCP (default port 1883);
98
+ * "mqtts://host:port" is TLS (default 8883). A bare "host" or "host:port"
99
+ * works too, and an IPv6 literal is bracketed ("mqtt://[::1]:1883").
100
+ * Credentials ride in the userinfo and are percent-decoded, so a password
101
+ * containing @ : or / survives.
102
+ */
103
+ static parseUrl(url: string): ParsedMqttUrl;
104
+ /**
105
+ * Decode %XX in url userinfo. NOT decodeURI-style "+"-to-space: a "+" in a
106
+ * password must survive verbatim, and an invalid "%" is left as-is (never throws).
107
+ */
108
+ private static percentDecode;
109
+ /**
110
+ * Remaining Length varint: 7 bits per byte, high bit means "another byte
111
+ * follows". A single-byte assumption works for every packet under 128 bytes
112
+ * and then fails, so this is exercised directly at 0 / 127 / 128 / 16383.
113
+ */
114
+ static encodeRemainingLength(value: number): Buffer;
115
+ /**
116
+ * Open the socket and complete the CONNECT / CONNACK handshake. Also the
117
+ * reconnect path: an existing socket is closed first, and a durable session
118
+ * (cleanSession false) resumes with the same clientId. Returns this for
119
+ * chaining (`const c = await new Mqtt(opts).connect()`).
120
+ */
121
+ connect(): Promise<this>;
122
+ /** Whether a socket is currently open. */
123
+ connected(): boolean;
124
+ /** True when this connection runs over TLS (mqtts://). */
125
+ tls(): boolean;
126
+ /**
127
+ * The negotiated cipher suite name, or null on a plain connection. A real name
128
+ * here is proof the TLS handshake actually completed.
129
+ */
130
+ cipher(): string | null;
131
+ /** The negotiated TLS protocol version ("TLSv1.3"), or null when plain. */
132
+ tlsVersion(): string | null;
133
+ /**
134
+ * Publish an application message. Resolves to the packet identifier for QoS 1
135
+ * (the broker's PUBACK must carry it back) and null for QoS 0.
136
+ *
137
+ * retain=true tells the broker to keep this as the topic's last known value and
138
+ * hand it to every FUTURE subscriber. Publishing an EMPTY payload with
139
+ * retain=true clears a retained value.
140
+ */
141
+ publish(topic: string, payload: unknown, qos?: number, retain?: boolean): Promise<number | null>;
142
+ /**
143
+ * Subscribe to a topic filter ("fleet/+/telemetry", "fleet/#"). Resolves to the
144
+ * QoS the broker GRANTED, which can be lower than requested.
145
+ *
146
+ * A SUBACK carrying 0x80 is a REFUSAL, not a success -- treating any SUBACK as
147
+ * success means sitting on a dead subscription receiving nothing, so it throws.
148
+ */
149
+ subscribe(topicFilter: string, qos?: number): Promise<number>;
150
+ /**
151
+ * Read the next application message.
152
+ *
153
+ * ack=true (the default) acknowledges a QoS 1 delivery immediately, which is
154
+ * right for a synchronous read. Pass ack=false when the message must be stored
155
+ * before the broker is allowed to forget it -- an unacknowledged QoS 1 message
156
+ * is redelivered with DUP set. consume() does exactly that.
157
+ */
158
+ receive(timeout?: number | null, ack?: boolean): Promise<MqttMessage>;
159
+ /**
160
+ * Long-running consumer, mirroring Queue.consume().
161
+ *
162
+ * for await (const message of mqtt.consume("fleet/+/telemetry", 1)) {
163
+ * store(message);
164
+ * }
165
+ *
166
+ * The message is acknowledged AFTER the loop body hands control back to the
167
+ * generator (the next iteration), so a body that throws leaves the message
168
+ * unacknowledged and the broker redelivers it with DUP set -- at-least-once,
169
+ * the point of QoS 1. iterations > 0 stops after that many messages.
170
+ */
171
+ consume(topicFilter?: string | null, qos?: number, iterations?: number, timeout?: number | null): AsyncGenerator<MqttMessage>;
172
+ /** PUBACK a QoS 1 delivery. Called by MqttMessage.acknowledge(). */
173
+ acknowledge(packetId: number): Promise<boolean>;
174
+ /**
175
+ * PINGREQ and wait for the PINGRESP. Use this when nothing else is reading the
176
+ * socket; under a consume loop use startKeepalive() instead.
177
+ */
178
+ ping(timeout?: number | null): Promise<boolean>;
179
+ /**
180
+ * Write a PINGREQ without waiting for the answer. The PINGRESP is absorbed by
181
+ * whatever is reading the socket (receive() skips it).
182
+ */
183
+ sendKeepalive(): Promise<boolean>;
184
+ /**
185
+ * Opt in to the cooperative keepalive. Registers a background() task -- the
186
+ * same mechanism the queue consumers use -- that sends a PINGREQ only when the
187
+ * connection has gone quiet, so an actively publishing client costs no extra
188
+ * packets.
189
+ */
190
+ startKeepalive(intervalSeconds?: number): {
191
+ stop: () => void;
192
+ };
193
+ /** Stop the cooperative keepalive registered by startKeepalive(). */
194
+ stopKeepalive(): boolean;
195
+ /**
196
+ * Say goodbye properly: DISCONNECT then close. The broker discards the Last
197
+ * Will on a graceful disconnect.
198
+ */
199
+ disconnect(): Promise<boolean>;
200
+ /**
201
+ * Drop the socket WITHOUT a DISCONNECT -- what a crashed or unplugged device
202
+ * looks like to the broker, and therefore what fires the Last Will.
203
+ */
204
+ kill(): boolean;
205
+ private connectFlags;
206
+ /**
207
+ * Open a connected socket, upgrading to TLS when mqtts://. Rejects with an
208
+ * MqttError on a connect timeout or a TLS verification failure (the cert error
209
+ * message is preserved so a rejected cert reports WHY). Each connection builds
210
+ * its OWN tls options object, so a CA supplied for one client never leaks into
211
+ * a later client.
212
+ */
213
+ private openSocket;
214
+ private refuseUnsupportedQos;
215
+ /** Encode an MQTT string: a 2-byte big-endian length followed by UTF-8 bytes. */
216
+ private static mqttString;
217
+ private static uint16;
218
+ private static payloadBytes;
219
+ /** The next packet identifier (1..65535; 0 is invalid). */
220
+ private nextPacketId;
221
+ private writePacket;
222
+ /**
223
+ * Read one control packet. The fixed header is read in exactly 1 + N bytes
224
+ * (N <= 4 for the varint) so the next packet's header is never consumed by a
225
+ * speculative over-read.
226
+ */
227
+ private readPacket;
228
+ /**
229
+ * Read exactly `need` bytes from the socket buffer, awaiting more data when
230
+ * short. Only one read is ever outstanding (the protocol reads sequentially),
231
+ * so a single waiter slot is enough. The 'data' handler feeds the buffer and
232
+ * services the waiter; a deadline arms a timer that rejects with a timeout.
233
+ */
234
+ private readExact;
235
+ private take;
236
+ private serviceWaiter;
237
+ private onData;
238
+ private onSocketGone;
239
+ /** Read packets until the next PUBLISH, skipping keepalive PINGRESPs. */
240
+ private readPublish;
241
+ /**
242
+ * Park a PUBLISH that arrives while we wait for a PUBACK/SUBACK/PINGRESP
243
+ * (normal when the same connection both publishes and subscribes) so receive()
244
+ * still delivers it, in order, instead of it being mistaken for the ack.
245
+ */
246
+ private stashPublish;
247
+ private parsePublish;
248
+ /**
249
+ * Wait for a specific acknowledgement, tolerating interleaved PUBLISH and
250
+ * PINGRESP packets. A mismatched packet identifier is silent data loss if
251
+ * ignored, so it throws.
252
+ */
253
+ private waitForAcknowledgement;
254
+ private idleFor;
255
+ private deadlineIn;
256
+ private closeSocket;
257
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * One MQTT 3.1.1 application message as delivered by the broker.
3
+ *
4
+ * Shaped like the Queue's job (its unit of work): it carries the payload plus
5
+ * the delivery metadata a consumer needs, and it knows how to acknowledge itself
6
+ * back to the client it came from. Mirrors tina4_python.mqtt.MqttMessage,
7
+ * Tina4::MqttMessage (Ruby), and Tina4\MqttMessage (PHP).
8
+ *
9
+ * The two flags matter for correctness, not decoration:
10
+ *
11
+ * retained — the broker replayed the topic's last known value to us because
12
+ * we subscribed AFTER it was published. It is current state, not a
13
+ * fresh event.
14
+ * duplicate — the DUP flag. The broker is REDELIVERING a QoS 1 message it never
15
+ * saw acknowledged. QoS 1 is at-least-once, so a duplicate is
16
+ * guaranteed eventually; a consumer that treats a DUP delivery as a
17
+ * new sample double-counts energy or mileage. Key the ingest on
18
+ * (deviceId, deviceTimestamp) and it is harmless.
19
+ *
20
+ * The payload is a Buffer of the raw bytes; text() decodes it for JSON/string
21
+ * payloads.
22
+ */
23
+ /** The slice of an Mqtt client an MqttMessage needs to acknowledge itself. */
24
+ export interface MqttAcknowledger {
25
+ acknowledge(packetId: number): Promise<boolean>;
26
+ }
27
+ export declare class MqttMessage {
28
+ readonly topic: string;
29
+ readonly payload: Buffer;
30
+ readonly qos: number;
31
+ readonly retained: boolean;
32
+ readonly duplicate: boolean;
33
+ readonly packetId: number | null;
34
+ private readonly client;
35
+ private acknowledgedFlag;
36
+ constructor(topic: string, payload: Buffer, qos?: number, retained?: boolean, duplicate?: boolean, packetId?: number | null, client?: MqttAcknowledger | null);
37
+ /** True when the broker replayed this as the topic's retained (last known) value. */
38
+ isRetained(): boolean;
39
+ /**
40
+ * True when the broker set the DUP flag — a REDELIVERY of a QoS 1 message we
41
+ * never acknowledged, not a new sample.
42
+ */
43
+ isDuplicate(): boolean;
44
+ /**
45
+ * PUBACK a QoS 1 delivery so the broker stops redelivering it.
46
+ *
47
+ * A QoS 0 message needs no acknowledgement, and a second call is a no-op, so
48
+ * this is always safe to call once processing succeeded. Returns true only
49
+ * when a PUBACK was actually sent.
50
+ */
51
+ acknowledge(): Promise<boolean>;
52
+ /** True once this message has been acknowledged back to the broker. */
53
+ isAcknowledged(): boolean;
54
+ /** The payload decoded as text (for JSON / string payloads). */
55
+ text(encoding?: BufferEncoding): string;
56
+ /** The message as a plain object. */
57
+ toObject(): {
58
+ topic: string;
59
+ payload: Buffer;
60
+ qos: number;
61
+ retained: boolean;
62
+ duplicate: boolean;
63
+ packetId: number | null;
64
+ };
65
+ /** String form is the payload text (parity with Python __str__ / Ruby to_s). */
66
+ toString(): string;
67
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Project plan management — persistent, human-readable task state.
3
+ *
4
+ * Ported from tina4_python/dev_admin/plan.py (master reference).
5
+ * A plan is a markdown file under plan/ at the project root with sections
6
+ * for title, goal, steps (checkboxes), and notes. Exactly one plan is
7
+ * "current" at a time, recorded in plan/.current.
8
+ *
9
+ * Byte-for-byte compatible with Python's plan/*.md storage.
10
+ */
11
+ export interface PlanStep {
12
+ text: string;
13
+ done: boolean;
14
+ index?: number;
15
+ }
16
+ export interface ParsedPlan {
17
+ title: string;
18
+ goal: string;
19
+ steps: PlanStep[];
20
+ notes: string;
21
+ }
22
+ export interface PlanSummary {
23
+ name: string;
24
+ title: string;
25
+ steps_total: number;
26
+ steps_done: number;
27
+ is_current: boolean;
28
+ /** Path relative to project root — lets the SPA open the right file
29
+ * regardless of which dir the plan came from (plan/ vs .tina4/plans/). */
30
+ path: string;
31
+ }
32
+ export interface ExecutionSummary {
33
+ created: string[];
34
+ patched: string[];
35
+ migrations: string[];
36
+ total: number;
37
+ }
38
+ export interface CurrentPlan {
39
+ current: string | null;
40
+ title?: string;
41
+ goal?: string;
42
+ steps?: PlanStep[];
43
+ next_step?: PlanStep | null;
44
+ notes?: string;
45
+ progress?: {
46
+ done: number;
47
+ total: number;
48
+ };
49
+ execution?: ExecutionSummary;
50
+ warning?: string;
51
+ }
52
+ export declare const Plan: {
53
+ /**
54
+ * All plan files — merged from `plan/` (user-curated canonical) and
55
+ * `.tina4/plans/` (where the Rust supervisor's planner writes).
56
+ *
57
+ * Two directories exist because of a historic split: the framework
58
+ * treats `plan/` as the canonical project location, but the Rust agent's
59
+ * planner writes to `.tina4/plans/` (alongside other AI-state artefacts
60
+ * like chat history). Until those are unified we read both so plans
61
+ * created either way are discoverable. Dedup by filename when a plan
62
+ * exists in both — `plan/` wins on collision.
63
+ *
64
+ * Newest-first by filename (Rust planner uses unix-timestamp prefixes).
65
+ */
66
+ listPlans(): PlanSummary[];
67
+ currentName(): string;
68
+ setCurrent(name: string): {
69
+ ok: boolean;
70
+ current?: string;
71
+ error?: string;
72
+ };
73
+ clearCurrent(): {
74
+ ok: boolean;
75
+ };
76
+ current(): CurrentPlan;
77
+ read(name: string): ParsedPlan & {
78
+ name?: string;
79
+ error?: string;
80
+ };
81
+ create(title: string, goal?: string, steps?: string[], makeCurrent?: boolean): {
82
+ ok: boolean;
83
+ name?: string;
84
+ title?: string;
85
+ is_current?: boolean;
86
+ error?: string;
87
+ };
88
+ completeStep(index: number, name?: string): Record<string, unknown>;
89
+ uncompleteStep(index: number, name?: string): Record<string, unknown>;
90
+ addStep(text: string, name?: string): Record<string, unknown>;
91
+ appendNote(text: string, name?: string): Record<string, unknown>;
92
+ recordAction(action: string, filePath: string, note?: string): void;
93
+ summariseExecution(name?: string): ExecutionSummary;
94
+ flesh(name?: string, prompt?: string): Promise<Record<string, unknown>>;
95
+ archive(name?: string): Record<string, unknown>;
96
+ };
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Project index — lightweight, persistent "where is what" map.
3
+ *
4
+ * Ported from tina4_python/dev_admin/project_index.py (master reference).
5
+ *
6
+ * Storage: .tina4/project_index.json at the project root.
7
+ * Freshness: lazy-refreshes on read via mtime compare — no watchers.
8
+ * Extractors: per-language symbol extraction (TS/JS, Twig/HTML, SQL, Markdown,
9
+ * Python) using regex. No LLM involvement — pure static analysis.
10
+ */
11
+ export interface FileRoute {
12
+ method: string;
13
+ path: string;
14
+ handler: string;
15
+ }
16
+ export interface FileEntry {
17
+ path?: string;
18
+ size?: number;
19
+ mtime?: number;
20
+ language?: string;
21
+ sha256?: string;
22
+ skipped?: string;
23
+ extraction_error?: string;
24
+ summary?: string;
25
+ symbols?: string[];
26
+ imports?: string[];
27
+ routes?: FileRoute[];
28
+ docstring?: string;
29
+ exports?: string[];
30
+ extends?: string[];
31
+ blocks?: string[];
32
+ includes?: string[];
33
+ creates?: string[];
34
+ alters?: string[];
35
+ title?: string;
36
+ sections?: string[];
37
+ first_line?: string;
38
+ error?: string;
39
+ }
40
+ export declare const ProjectIndex: {
41
+ refresh(): {
42
+ added: number;
43
+ updated: number;
44
+ removed: number;
45
+ total: number;
46
+ path: string;
47
+ };
48
+ search(query: string, limit?: number): Array<{
49
+ path: string;
50
+ summary: string;
51
+ score: number;
52
+ language: string;
53
+ }>;
54
+ fileEntry(relPath: string): FileEntry;
55
+ overview(): Record<string, unknown>;
56
+ };