@pikku/core 0.12.14 → 0.12.16

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 (136) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/dist/errors/errors.d.ts +4 -0
  3. package/dist/errors/errors.js +12 -0
  4. package/dist/function/function-runner.js +2 -1
  5. package/dist/function/functions.types.js +1 -0
  6. package/dist/function/index.d.ts +2 -1
  7. package/dist/function/index.js +1 -0
  8. package/dist/handle-error.d.ts +2 -2
  9. package/dist/handle-error.js +8 -8
  10. package/dist/index.d.ts +2 -3
  11. package/dist/index.js +1 -2
  12. package/dist/middleware/index.d.ts +3 -0
  13. package/dist/middleware/index.js +3 -0
  14. package/dist/middleware/remote-auth.js +5 -2
  15. package/dist/middleware/telemetry.d.ts +47 -0
  16. package/dist/middleware/telemetry.js +106 -0
  17. package/dist/middleware-runner.js +31 -4
  18. package/dist/permissions.d.ts +13 -1
  19. package/dist/permissions.js +51 -0
  20. package/dist/pikku-state.d.ts +0 -1
  21. package/dist/pikku-state.js +1 -4
  22. package/dist/remote.d.ts +10 -0
  23. package/dist/remote.js +32 -0
  24. package/dist/schema.js +2 -0
  25. package/dist/services/deployment-service.d.ts +12 -1
  26. package/dist/services/in-memory-queue-service.d.ts +7 -0
  27. package/dist/services/in-memory-queue-service.js +28 -0
  28. package/dist/services/index.d.ts +4 -1
  29. package/dist/services/index.js +2 -1
  30. package/dist/services/logger-console.d.ts +26 -40
  31. package/dist/services/logger-console.js +102 -46
  32. package/dist/services/logger.d.ts +5 -0
  33. package/dist/services/meta-service.d.ts +175 -0
  34. package/dist/services/meta-service.js +310 -0
  35. package/dist/services/workflow-service.d.ts +6 -1
  36. package/dist/testing/service-tests.js +0 -8
  37. package/dist/types/core.types.d.ts +21 -0
  38. package/dist/types/core.types.js +7 -1
  39. package/dist/types/state.types.d.ts +2 -2
  40. package/dist/wirings/ai-agent/ai-agent-prepare.js +42 -21
  41. package/dist/wirings/ai-agent/ai-agent-registry.js +2 -2
  42. package/dist/wirings/ai-agent/ai-agent-runner.js +18 -1
  43. package/dist/wirings/ai-agent/ai-agent-stream.js +1 -0
  44. package/dist/wirings/ai-agent/ai-agent.types.d.ts +5 -3
  45. package/dist/wirings/channel/channel-runner.js +3 -3
  46. package/dist/wirings/cli/cli-runner.js +5 -3
  47. package/dist/wirings/cli/command-parser.js +7 -3
  48. package/dist/wirings/http/http-runner.d.ts +1 -1
  49. package/dist/wirings/http/http-runner.js +23 -11
  50. package/dist/wirings/http/http.types.d.ts +3 -0
  51. package/dist/wirings/http/pikku-fetch-http-response.d.ts +1 -0
  52. package/dist/wirings/http/pikku-fetch-http-response.js +3 -0
  53. package/dist/wirings/mcp/mcp-runner.js +5 -3
  54. package/dist/wirings/mcp/mcp.types.d.ts +1 -1
  55. package/dist/wirings/queue/queue-runner.d.ts +3 -1
  56. package/dist/wirings/queue/queue-runner.js +7 -3
  57. package/dist/wirings/rpc/rpc-runner.js +56 -90
  58. package/dist/wirings/scheduler/scheduler-runner.d.ts +3 -1
  59. package/dist/wirings/scheduler/scheduler-runner.js +9 -5
  60. package/dist/wirings/trigger/trigger-runner.js +4 -2
  61. package/dist/wirings/workflow/dsl/workflow-runner.d.ts +1 -1
  62. package/dist/wirings/workflow/dsl/workflow-runner.js +6 -9
  63. package/dist/wirings/workflow/graph/graph-runner.d.ts +1 -1
  64. package/dist/wirings/workflow/graph/graph-runner.js +18 -4
  65. package/dist/wirings/workflow/index.d.ts +4 -2
  66. package/dist/wirings/workflow/index.js +4 -2
  67. package/dist/wirings/workflow/pikku-workflow-service.d.ts +16 -4
  68. package/dist/wirings/workflow/pikku-workflow-service.js +216 -24
  69. package/dist/wirings/workflow/workflow-queue-workers.d.ts +40 -0
  70. package/dist/wirings/workflow/workflow-queue-workers.js +41 -0
  71. package/dist/wirings/workflow/workflow.types.d.ts +17 -1
  72. package/package.json +4 -1
  73. package/src/errors/errors.ts +12 -0
  74. package/src/function/function-runner.ts +5 -4
  75. package/src/function/functions.types.ts +1 -0
  76. package/src/function/index.ts +10 -0
  77. package/src/handle-error.test.ts +2 -2
  78. package/src/handle-error.ts +8 -8
  79. package/src/index.ts +2 -2
  80. package/src/middleware/index.ts +3 -0
  81. package/src/middleware/remote-auth.test.ts +4 -4
  82. package/src/middleware/remote-auth.ts +7 -2
  83. package/src/middleware/telemetry.ts +110 -0
  84. package/src/middleware-runner.test.ts +149 -1
  85. package/src/middleware-runner.ts +48 -4
  86. package/src/permissions.ts +70 -0
  87. package/src/pikku-state.test.ts +0 -26
  88. package/src/pikku-state.ts +1 -5
  89. package/src/remote.ts +46 -0
  90. package/src/schema.ts +1 -0
  91. package/src/services/deployment-service.ts +17 -1
  92. package/src/services/in-memory-queue-service.ts +46 -0
  93. package/src/services/index.ts +21 -1
  94. package/src/services/logger-console.ts +127 -47
  95. package/src/services/logger.ts +6 -0
  96. package/src/services/meta-service.ts +523 -0
  97. package/src/services/workflow-service.ts +8 -0
  98. package/src/testing/service-tests.ts +0 -10
  99. package/src/types/core.types.ts +36 -1
  100. package/src/types/state.types.ts +2 -2
  101. package/src/wirings/ai-agent/ai-agent-prepare.ts +51 -40
  102. package/src/wirings/ai-agent/ai-agent-registry.ts +3 -3
  103. package/src/wirings/ai-agent/ai-agent-runner.ts +16 -1
  104. package/src/wirings/ai-agent/ai-agent-stream.ts +8 -0
  105. package/src/wirings/ai-agent/ai-agent.types.ts +5 -3
  106. package/src/wirings/channel/channel-runner.ts +4 -5
  107. package/src/wirings/channel/local/local-channel-runner.test.ts +5 -1
  108. package/src/wirings/cli/cli-runner.test.ts +8 -7
  109. package/src/wirings/cli/cli-runner.ts +6 -4
  110. package/src/wirings/cli/command-parser.ts +8 -3
  111. package/src/wirings/http/http-runner.ts +27 -11
  112. package/src/wirings/http/http.types.ts +3 -0
  113. package/src/wirings/http/pikku-fetch-http-response.ts +4 -0
  114. package/src/wirings/mcp/mcp-runner.ts +7 -9
  115. package/src/wirings/mcp/mcp.types.ts +1 -1
  116. package/src/wirings/queue/queue-runner.test.ts +5 -11
  117. package/src/wirings/queue/queue-runner.ts +11 -3
  118. package/src/wirings/rpc/rpc-runner.ts +82 -115
  119. package/src/wirings/scheduler/scheduler-runner.test.ts +5 -11
  120. package/src/wirings/scheduler/scheduler-runner.ts +13 -5
  121. package/src/wirings/trigger/trigger-runner.test.ts +10 -11
  122. package/src/wirings/trigger/trigger-runner.ts +6 -4
  123. package/src/wirings/workflow/dsl/workflow-runner.ts +11 -10
  124. package/src/wirings/workflow/graph/graph-runner.ts +19 -4
  125. package/src/wirings/workflow/index.ts +17 -6
  126. package/src/wirings/workflow/pikku-workflow-service.ts +284 -24
  127. package/src/wirings/workflow/workflow-queue-workers.ts +85 -0
  128. package/src/wirings/workflow/workflow.types.ts +16 -1
  129. package/tsconfig.tsbuildinfo +1 -1
  130. package/dist/wirings/ai-agent/agent-dynamic-workflow.d.ts +0 -6
  131. package/dist/wirings/ai-agent/agent-dynamic-workflow.js +0 -468
  132. package/dist/wirings/workflow/workflow-helpers.d.ts +0 -36
  133. package/dist/wirings/workflow/workflow-helpers.js +0 -38
  134. package/src/wirings/ai-agent/agent-dynamic-workflow.ts +0 -610
  135. package/src/wirings/workflow/workflow-helpers.test.ts +0 -129
  136. package/src/wirings/workflow/workflow-helpers.ts +0 -79
package/CHANGELOG.md CHANGED
@@ -1,5 +1,41 @@
1
1
  ## 0.12.4
2
2
 
3
+ ## 0.12.16
4
+
5
+ ### Patch Changes
6
+
7
+ - fbcf5b9: Add middleware priority system, telemetry middleware, and statusCode getter. Middleware now supports named priority levels (highest, high, medium, low, lowest) that control execution order regardless of registration order. Includes telemetryOuter and telemetryInner middleware for observability instrumentation via structured console.log output. PikkuHTTPResponse now exposes a readonly `statusCode` getter across all response implementations.
8
+
9
+ ## 0.12.15
10
+
11
+ ### Patch Changes
12
+
13
+ - 9e8605f: Add Workers for Platforms dispatch namespace support and AI agent fixes.
14
+
15
+ - deploy-cloudflare: Thread dispatchNamespace through deploy pipeline, reads CF_DISPATCH_NAMESPACE env var
16
+ - core: Fix auth-gated tools visible to unauthenticated sessions (null session now hides permission-gated items)
17
+ - core: Recursive null stripping in AI agent tool call resume path
18
+ - ai-vercel: Handle anyOf/oneOf/array types when making optional fields nullable for strict providers
19
+
20
+ - 624097e: Add deploy pipeline with provider-agnostic architecture
21
+
22
+ - Add MetaService with explicit typed API, absorb WiringService reads
23
+ - Add deployment service, traceId propagation, scoped logger
24
+ - Rewrite analyzer: one function = one worker, gateways dispatch via RPC
25
+ - Add Cloudflare deploy provider with plan/apply commands
26
+ - Add per-unit filtered codegen for deploy pipeline
27
+ - Skip missing metadata in wiring registration for deploy units
28
+ - Fix schema coercion crash when schema has no properties
29
+ - Fix E2E codegen: double-pass resolves cross-package Zod type imports
30
+
31
+ - 7ab3243: Add server-fallback deployment target for functions that can't run serverless.
32
+
33
+ Functions can declare `deploy: 'serverless' | 'server' | 'auto'`. With `serverlessIncompatible` config, the analyzer auto-routes functions using incompatible services to a container.
34
+
35
+ Server functions are merged into a single tree-shaken unit with a PikkuUWSServer entry, Dockerfile, and CF Container proxy Worker.
36
+
37
+ Also adds sub-path exports to @pikku/cloudflare for tree-shaking (greet bundle 1.6MB → 444KB) and deploy verifiers for cloudflare, serverless, and azure providers.
38
+
3
39
  ## 0.12.14
4
40
 
5
41
  ### Patch Changes
@@ -6,6 +6,10 @@ export declare class InvalidMiddlewareWireError extends PikkuError {
6
6
  }
7
7
  export declare class PikkuMissingMetaError extends PikkuError {
8
8
  }
9
+ export declare class MissingServiceError extends PikkuError {
10
+ }
11
+ export declare class LocalEnvironmentOnlyError extends PikkuError {
12
+ }
9
13
  /**
10
14
  * The server cannot or will not process the request due to client error (e.g., malformed request syntax).
11
15
  * @group Error
@@ -14,6 +14,18 @@ addError(PikkuMissingMetaError, {
14
14
  status: 500,
15
15
  message: 'Required metadata is missing',
16
16
  });
17
+ export class MissingServiceError extends PikkuError {
18
+ }
19
+ addError(MissingServiceError, {
20
+ status: 500,
21
+ message: 'A required service is not configured',
22
+ });
23
+ export class LocalEnvironmentOnlyError extends PikkuError {
24
+ }
25
+ addError(LocalEnvironmentOnlyError, {
26
+ status: 403,
27
+ message: 'This operation is only available in local development mode',
28
+ });
17
29
  /**
18
30
  * The server cannot or will not process the request due to client error (e.g., malformed request syntax).
19
31
  * @group Error
@@ -196,8 +196,9 @@ export const runPikkuFunc = async (wireType, wireId, funcName, { singletonServic
196
196
  packageName,
197
197
  });
198
198
  }
199
- const wireServices = await resolvedCreateWireServices?.(resolvedSingletonServices, resolvedWire);
199
+ let wireServices;
200
200
  try {
201
+ wireServices = (await resolvedCreateWireServices?.(resolvedSingletonServices, resolvedWire));
201
202
  const services = wireServices && Object.keys(wireServices).length > 0
202
203
  ? { ...resolvedSingletonServices, ...wireServices }
203
204
  : resolvedSingletonServices;
@@ -73,5 +73,6 @@ export const pikkuAuth = (auth) => {
73
73
  return false;
74
74
  return fn(services, session);
75
75
  };
76
+ wrapper.__pikkuAuth = true;
76
77
  return wrapper;
77
78
  };
@@ -1,2 +1,3 @@
1
1
  export { addFunction, getAllFunctionNames } from './function-runner.js';
2
- export type { CorePikkuFunction, CorePikkuFunctionSessionless, } from './functions.types.js';
2
+ export { pikkuAuth, pikkuPermission, pikkuPermissionFactory, pikkuApprovalDescription, } from './functions.types.js';
3
+ export type { CorePikkuFunction, CorePikkuFunctionSessionless, CorePikkuFunctionConfig, CorePikkuAuth, CorePikkuAuthConfig, CorePikkuPermission, } from './functions.types.js';
@@ -1 +1,2 @@
1
1
  export { addFunction, getAllFunctionNames } from './function-runner.js';
2
+ export { pikkuAuth, pikkuPermission, pikkuPermissionFactory, pikkuApprovalDescription, } from './functions.types.js';
@@ -5,10 +5,10 @@ import type { PikkuHTTP } from './wirings/http/http.types.js';
5
5
  *
6
6
  * @param {any} e - The error that occurred
7
7
  * @param {PikkuHTTP | undefined} http - HTTP wire object
8
- * @param {string} trackerId - Unique ID for tracking this error
8
+ * @param {string} traceId - Unique ID for tracking this error
9
9
  * @param {Logger} logger - Logger service
10
10
  * @param {number[]} logWarningsForStatusCodes - HTTP status codes to log as warnings
11
11
  * @param {boolean} respondWith404 - Whether to respond with 404 for NotFoundError
12
12
  * @param {boolean} bubbleError - Whether to throw the error after handling
13
13
  */
14
- export declare const handleHTTPError: (e: any, http: PikkuHTTP | undefined, trackerId: string | undefined, logger: Logger, logWarningsForStatusCodes: number[], respondWith404: boolean, bubbleError: boolean, exposeErrors?: boolean) => void;
14
+ export declare const handleHTTPError: (e: any, http: PikkuHTTP | undefined, traceId: string | undefined, logger: Logger, logWarningsForStatusCodes: number[], respondWith404: boolean, bubbleError: boolean, exposeErrors?: boolean) => void;
@@ -6,13 +6,13 @@ import { NotFoundError } from './errors/errors.js';
6
6
  *
7
7
  * @param {any} e - The error that occurred
8
8
  * @param {PikkuHTTP | undefined} http - HTTP wire object
9
- * @param {string} trackerId - Unique ID for tracking this error
9
+ * @param {string} traceId - Unique ID for tracking this error
10
10
  * @param {Logger} logger - Logger service
11
11
  * @param {number[]} logWarningsForStatusCodes - HTTP status codes to log as warnings
12
12
  * @param {boolean} respondWith404 - Whether to respond with 404 for NotFoundError
13
13
  * @param {boolean} bubbleError - Whether to throw the error after handling
14
14
  */
15
- export const handleHTTPError = (e, http, trackerId, logger, logWarningsForStatusCodes, respondWith404, bubbleError, exposeErrors = false) => {
15
+ export const handleHTTPError = (e, http, traceId, logger, logWarningsForStatusCodes, respondWith404, bubbleError, exposeErrors = false) => {
16
16
  // Skip 404 handling if configured to do so
17
17
  if (e instanceof NotFoundError && !respondWith404) {
18
18
  return;
@@ -25,12 +25,12 @@ export const handleHTTPError = (e, http, trackerId, logger, logWarningsForStatus
25
25
  http?.response?.json({
26
26
  message: errorResponse.message,
27
27
  payload: e.payload,
28
- traceId: trackerId,
28
+ errorId: traceId,
29
29
  });
30
30
  // Log certain status codes as warnings
31
31
  if (logWarningsForStatusCodes.includes(errorResponse.status)) {
32
- if (trackerId) {
33
- logger.warn(`Warning id: ${trackerId}`);
32
+ if (traceId) {
33
+ logger.warn(`Warning id: ${traceId}`);
34
34
  }
35
35
  logger.warn(e instanceof Error ? e.message : e);
36
36
  }
@@ -39,9 +39,9 @@ export const handleHTTPError = (e, http, trackerId, logger, logWarningsForStatus
39
39
  // Handle unexpected errors
40
40
  logger.error(e instanceof Error ? e.message : e);
41
41
  http?.response?.status(500);
42
- if (trackerId) {
43
- logger.warn(`Error id: ${trackerId}`);
44
- const errorBody = { errorId: trackerId };
42
+ if (traceId) {
43
+ logger.warn(`Error id: ${traceId}`);
44
+ const errorBody = { errorId: traceId };
45
45
  if (exposeErrors && !isProduction() && e instanceof Error) {
46
46
  errorBody.message = e.message;
47
47
  errorBody.stack = e.stack;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * @module @pikku/core
3
3
  */
4
- export type { CommonWireMeta, CoreConfig, CorePikkuMiddleware, CorePikkuMiddlewareConfig, CorePikkuMiddlewareFactory, CorePikkuMiddlewareGroup, CoreServices, CoreSingletonServices, CoreUserSession, CreateConfig, FunctionMeta, FunctionRuntimeMeta, FunctionServicesMeta, FunctionWiresMeta, FunctionsMeta, FunctionsRuntimeMeta, JSONPrimitive, JSONValue, MakeRequired, MiddlewareMetadata, PermissionMetadata, PickOptional, PickRequired, PikkuAIMiddlewareHooks, PikkuWire, PikkuWiringTypes, RequireAtLeastOne, SerializedError, WireServices, } from './types/core.types.js';
4
+ export type { CommonWireMeta, CoreConfig, CorePikkuMiddleware, CorePikkuMiddlewareConfig, CorePikkuMiddlewareFactory, CorePikkuMiddlewareGroup, CoreServices, CoreSingletonServices, CoreUserSession, CreateConfig, FunctionMeta, FunctionRuntimeMeta, FunctionServicesMeta, FunctionWiresMeta, FunctionsMeta, FunctionsRuntimeMeta, JSONPrimitive, JSONValue, MakeRequired, MiddlewareMetadata, MiddlewarePriority, PermissionMetadata, PickOptional, PickRequired, PikkuAIMiddlewareHooks, PikkuWire, PikkuWiringTypes, RequireAtLeastOne, SerializedError, WireServices, } from './types/core.types.js';
5
5
  export { pikkuAIMiddleware, pikkuChannelMiddleware, pikkuChannelMiddlewareFactory, pikkuMiddleware, pikkuMiddlewareFactory, } from './types/core.types.js';
6
6
  export type { CorePikkuAuth, CorePikkuAuthConfig, CorePikkuFunction, CorePikkuFunctionConfig, CorePikkuPermission, CorePikkuPermissionConfig, CorePikkuPermissionFactory, CorePikkuApprovalDescription, CorePermissionGroup, ZodLike, } from './function/functions.types.js';
7
7
  export { pikkuAuth, pikkuPermission, pikkuPermissionFactory, pikkuApprovalDescription, } from './function/functions.types.js';
@@ -36,12 +36,11 @@ export type { AIStorageService } from './services/ai-storage-service.js';
36
36
  export type { HTTPMethod } from './wirings/http/http.types.js';
37
37
  export type { GraphNodeConfig } from './wirings/workflow/graph/workflow-graph.types.js';
38
38
  export { createGraph } from './wirings/workflow/graph/graph-node.js';
39
- export { workflow as wireWorkflow } from './wirings/workflow/workflow-helpers.js';
40
39
  export { wireAddon } from './wirings/rpc/wire-addon.js';
41
40
  export type { WireAddonConfig } from './wirings/rpc/wire-addon.js';
42
41
  export type { PikkuPackageState } from './types/state.types.js';
43
42
  export { runMiddleware, addMiddleware } from './middleware-runner.js';
44
- export { addPermission } from './permissions.js';
43
+ export { addPermission, checkAuthPermissions } from './permissions.js';
45
44
  export { isSerializable, stopSingletonServices } from './utils.js';
46
45
  export { getSingletonServices, getCreateWireServices } from './pikku-state.js';
47
46
  export { type ScheduledTaskInfo, type ScheduledTaskSummary, } from './services/scheduler-service.js';
package/dist/index.js CHANGED
@@ -12,10 +12,9 @@ export { runQueueJob } from './wirings/queue/queue-runner.js';
12
12
  export { runScheduledTask } from './wirings/scheduler/scheduler-runner.js';
13
13
  export { NotFoundError } from './errors/errors.js';
14
14
  export { createGraph } from './wirings/workflow/graph/graph-node.js';
15
- export { workflow as wireWorkflow } from './wirings/workflow/workflow-helpers.js';
16
15
  export { wireAddon } from './wirings/rpc/wire-addon.js';
17
16
  export { runMiddleware, addMiddleware } from './middleware-runner.js';
18
- export { addPermission } from './permissions.js';
17
+ export { addPermission, checkAuthPermissions } from './permissions.js';
19
18
  export { isSerializable, stopSingletonServices } from './utils.js';
20
19
  export { getSingletonServices, getCreateWireServices } from './pikku-state.js';
21
20
  export { SchedulerService } from './services/scheduler-service.js';
@@ -3,3 +3,6 @@ export { authCookie } from './auth-cookie.js';
3
3
  export { authBearer } from './auth-bearer.js';
4
4
  export { pikkuRemoteAuthMiddleware } from './remote-auth.js';
5
5
  export { cors } from './cors.js';
6
+ export { telemetryOuter, telemetryInner } from './telemetry.js';
7
+ export { addMiddleware, runMiddleware } from '../middleware-runner.js';
8
+ export { addPermission } from '../permissions.js';
@@ -3,3 +3,6 @@ export { authCookie } from './auth-cookie.js';
3
3
  export { authBearer } from './auth-bearer.js';
4
4
  export { pikkuRemoteAuthMiddleware } from './remote-auth.js';
5
5
  export { cors } from './cors.js';
6
+ export { telemetryOuter, telemetryInner } from './telemetry.js';
7
+ export { addMiddleware, runMiddleware } from '../middleware-runner.js';
8
+ export { addPermission } from '../permissions.js';
@@ -10,6 +10,9 @@ export const pikkuRemoteAuthMiddleware = pikkuMiddleware(async ({ secrets, jwt }
10
10
  secret = await secrets.getSecret('PIKKU_REMOTE_SECRET');
11
11
  }
12
12
  catch {
13
+ if (http.request.path().startsWith('/remote/rpc/')) {
14
+ throw new UnauthorizedError();
15
+ }
13
16
  return next();
14
17
  }
15
18
  if (!jwt) {
@@ -34,8 +37,8 @@ export const pikkuRemoteAuthMiddleware = pikkuMiddleware(async ({ secrets, jwt }
34
37
  if (payload?.aud !== 'pikku-remote') {
35
38
  throw new UnauthorizedError();
36
39
  }
37
- if (payload?.fn && http.request.path().startsWith('/rpc/')) {
38
- const fn = decodeURIComponent(http.request.path().slice('/rpc/'.length));
40
+ if (payload?.fn && http.request.path().startsWith('/remote/rpc/')) {
41
+ const fn = decodeURIComponent(http.request.path().slice('/remote/rpc/'.length));
39
42
  if (fn && payload.fn !== fn) {
40
43
  throw new UnauthorizedError();
41
44
  }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Outer telemetry middleware that captures total request duration and outcome.
3
+ * Runs at `highest` priority (outermost in the middleware chain).
4
+ *
5
+ * Emits a structured JSON log entry with `__pikku_telemetry: 'end'` containing:
6
+ * - Total duration (including all middleware)
7
+ * - Outcome (ok/error)
8
+ * - Wire metadata (wireType, wireId, traceId)
9
+ * - HTTP details (method, path, status) if applicable
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * import { telemetryOuter } from '@pikku/core/middleware'
14
+ * addMiddleware('myTag', [telemetryOuter()])
15
+ * ```
16
+ */
17
+ export declare const telemetryOuter: import("../types/core.types.js").CorePikkuMiddlewareFactory<void | {
18
+ environmentId?: string;
19
+ orgId?: string;
20
+ }, import("../types/core.types.js").CoreSingletonServices<{
21
+ logLevel?: import("../services/logger.js").LogLevel;
22
+ secrets?: {};
23
+ workflow?: import("../wirings/workflow/workflow.types.js").WorkflowServiceConfig;
24
+ }>, import("../types/core.types.js").CoreUserSession>;
25
+ /**
26
+ * Inner telemetry middleware that captures function execution duration and user context.
27
+ * Runs at `lowest` priority (innermost, closest to the function).
28
+ *
29
+ * Emits a structured JSON log entry with `__pikku_telemetry: 'end'` containing:
30
+ * - Function-only duration (excluding outer middleware like auth)
31
+ * - User identity (pikkuUserId) if authenticated
32
+ * - Wire metadata (wireType, wireId, traceId)
33
+ *
34
+ * @example
35
+ * ```typescript
36
+ * import { telemetryInner } from '@pikku/core/middleware'
37
+ * addMiddleware('myTag', [telemetryInner()])
38
+ * ```
39
+ */
40
+ export declare const telemetryInner: import("../types/core.types.js").CorePikkuMiddlewareFactory<void | {
41
+ environmentId?: string;
42
+ orgId?: string;
43
+ }, import("../types/core.types.js").CoreSingletonServices<{
44
+ logLevel?: import("../services/logger.js").LogLevel;
45
+ secrets?: {};
46
+ workflow?: import("../wirings/workflow/workflow.types.js").WorkflowServiceConfig;
47
+ }>, import("../types/core.types.js").CoreUserSession>;
@@ -0,0 +1,106 @@
1
+ import { pikkuMiddleware, pikkuMiddlewareFactory } from '../types/core.types.js';
2
+ /**
3
+ * Outer telemetry middleware that captures total request duration and outcome.
4
+ * Runs at `highest` priority (outermost in the middleware chain).
5
+ *
6
+ * Emits a structured JSON log entry with `__pikku_telemetry: 'end'` containing:
7
+ * - Total duration (including all middleware)
8
+ * - Outcome (ok/error)
9
+ * - Wire metadata (wireType, wireId, traceId)
10
+ * - HTTP details (method, path, status) if applicable
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * import { telemetryOuter } from '@pikku/core/middleware'
15
+ * addMiddleware('myTag', [telemetryOuter()])
16
+ * ```
17
+ */
18
+ export const telemetryOuter = pikkuMiddlewareFactory(({ environmentId, orgId } = {}) => {
19
+ return pikkuMiddleware({
20
+ name: 'telemetry-outer',
21
+ priority: 'highest',
22
+ func: async (services, wire, next) => {
23
+ const start = performance.now();
24
+ let outcome = 'ok';
25
+ let errorMessage;
26
+ try {
27
+ await next();
28
+ }
29
+ catch (e) {
30
+ outcome = 'error';
31
+ errorMessage = e instanceof Error ? e.message : String(e);
32
+ throw e;
33
+ }
34
+ finally {
35
+ services.logger.info({
36
+ __pikku_telemetry: 'end',
37
+ __pikku_layer: 'outer',
38
+ traceId: wire.traceId,
39
+ wireType: wire.wireType,
40
+ wireId: wire.wireId,
41
+ totalDuration: Math.round(performance.now() - start),
42
+ outcome,
43
+ ...(errorMessage ? { errorMessage } : {}),
44
+ ...(wire.http
45
+ ? {
46
+ httpStatus: wire.http.response?.statusCode,
47
+ httpMethod: wire.http.request?.method(),
48
+ httpPath: wire.http.request?.path(),
49
+ }
50
+ : {}),
51
+ ...(environmentId ? { environmentId } : {}),
52
+ ...(orgId ? { orgId } : {}),
53
+ });
54
+ }
55
+ },
56
+ });
57
+ });
58
+ /**
59
+ * Inner telemetry middleware that captures function execution duration and user context.
60
+ * Runs at `lowest` priority (innermost, closest to the function).
61
+ *
62
+ * Emits a structured JSON log entry with `__pikku_telemetry: 'end'` containing:
63
+ * - Function-only duration (excluding outer middleware like auth)
64
+ * - User identity (pikkuUserId) if authenticated
65
+ * - Wire metadata (wireType, wireId, traceId)
66
+ *
67
+ * @example
68
+ * ```typescript
69
+ * import { telemetryInner } from '@pikku/core/middleware'
70
+ * addMiddleware('myTag', [telemetryInner()])
71
+ * ```
72
+ */
73
+ export const telemetryInner = pikkuMiddlewareFactory(({ environmentId, orgId } = {}) => {
74
+ return pikkuMiddleware({
75
+ name: 'telemetry-inner',
76
+ priority: 'lowest',
77
+ func: async (services, wire, next) => {
78
+ const start = performance.now();
79
+ let outcome = 'ok';
80
+ let errorMessage;
81
+ try {
82
+ await next();
83
+ }
84
+ catch (e) {
85
+ outcome = 'error';
86
+ errorMessage = e instanceof Error ? e.message : String(e);
87
+ throw e;
88
+ }
89
+ finally {
90
+ services.logger.info({
91
+ __pikku_telemetry: 'end',
92
+ __pikku_layer: 'inner',
93
+ traceId: wire.traceId,
94
+ wireType: wire.wireType,
95
+ wireId: wire.wireId,
96
+ functionDuration: Math.round(performance.now() - start),
97
+ outcome,
98
+ pikkuUserId: wire.pikkuUserId,
99
+ ...(errorMessage ? { errorMessage } : {}),
100
+ ...(environmentId ? { environmentId } : {}),
101
+ ...(orgId ? { orgId } : {}),
102
+ });
103
+ }
104
+ },
105
+ });
106
+ });
@@ -1,5 +1,19 @@
1
1
  import { pikkuState } from './pikku-state.js';
2
2
  import { freezeDedupe, getTagGroups } from './utils.js';
3
+ const PRIORITY_ORDER = {
4
+ highest: 0,
5
+ high: 1,
6
+ medium: 2,
7
+ low: 3,
8
+ lowest: 4,
9
+ };
10
+ const getMiddlewarePriority = (fn) => {
11
+ const priority = fn.__priority;
12
+ return PRIORITY_ORDER[priority ?? 'medium'];
13
+ };
14
+ const sortByPriority = (middlewares) => {
15
+ return middlewares.sort((a, b) => getMiddlewarePriority(a) - getMiddlewarePriority(b));
16
+ };
3
17
  /**
4
18
  * Runs a chain of middleware functions in sequence before executing the main function.
5
19
  *
@@ -18,11 +32,14 @@ import { freezeDedupe, getTagGroups } from './utils.js';
18
32
  * );
19
33
  */
20
34
  export const runMiddleware = async (services, wire, middlewares, main) => {
21
- // Deduplicate middleware using Set to avoid running the same middleware multiple times
35
+ // Sort by priority if not already sorted (cached middleware is pre-sorted)
36
+ const sorted = isSortedByPriority(middlewares)
37
+ ? middlewares
38
+ : [...middlewares].sort((a, b) => getMiddlewarePriority(a) - getMiddlewarePriority(b));
22
39
  let result;
23
40
  const dispatch = async (index) => {
24
- if (middlewares && index < middlewares.length) {
25
- return await middlewares[index](services, wire, () => dispatch(index + 1));
41
+ if (sorted && index < sorted.length) {
42
+ return await sorted[index](services, wire, () => dispatch(index + 1));
26
43
  }
27
44
  else if (main) {
28
45
  result = await main();
@@ -31,6 +48,15 @@ export const runMiddleware = async (services, wire, middlewares, main) => {
31
48
  await dispatch(0);
32
49
  return result;
33
50
  };
51
+ const isSortedByPriority = (middlewares) => {
52
+ for (let i = 1; i < middlewares.length; i++) {
53
+ if (getMiddlewarePriority(middlewares[i]) <
54
+ getMiddlewarePriority(middlewares[i - 1])) {
55
+ return false;
56
+ }
57
+ }
58
+ return true;
59
+ };
34
60
  /**
35
61
  * Registers global middleware for a specific tag.
36
62
  *
@@ -176,7 +202,8 @@ export const combineMiddleware = (wireType, uid, { wireInheritedMiddleware, wire
176
202
  if (funcMiddleware) {
177
203
  resolved.push(...funcMiddleware);
178
204
  }
179
- // Deduplicate and freeze
205
+ // Sort by priority, deduplicate, and freeze
206
+ sortByPriority(resolved);
180
207
  middlewareCache[wireType][uid] = freezeDedupe(resolved);
181
208
  return middlewareCache[wireType][uid];
182
209
  };
@@ -1,4 +1,4 @@
1
- import type { CoreServices, PikkuWiringTypes, PermissionMetadata, PikkuWire } from './types/core.types.js';
1
+ import type { CoreServices, CoreUserSession, PikkuWiringTypes, PermissionMetadata, PikkuWire } from './types/core.types.js';
2
2
  import type { CorePermissionGroup, CorePikkuPermission } from './function/functions.types.js';
3
3
  /**
4
4
  * Adds global permissions for a specific tag.
@@ -44,3 +44,15 @@ export declare const runPermissions: (wireType: PikkuWiringTypes, uid: string, {
44
44
  data: any;
45
45
  packageName?: string | null;
46
46
  }) => Promise<void>;
47
+ /**
48
+ * Checks whether a session passes the auth checks (pikkuAuth only) for a
49
+ * given function/agent. Skips pikkuPermission checks since those require
50
+ * request data which isn't available at filter time.
51
+ *
52
+ * @param funcPermissions - The PermissionMetadata[] from function or agent metadata
53
+ * @param session - The user's session
54
+ * @param services - Singleton services
55
+ * @param packageName - Optional package namespace
56
+ * @returns true if the session passes all auth checks (or no auth checks exist)
57
+ */
58
+ export declare const checkAuthPermissions: (funcPermissions: PermissionMetadata[] | undefined, session: CoreUserSession, services: CoreServices, packageName?: string | null) => Promise<boolean>;
@@ -234,3 +234,54 @@ export const runPermissions = async (wireType, uid, { wireInheritedPermissions,
234
234
  throw new ForbiddenError('Permission denied');
235
235
  }
236
236
  };
237
+ /**
238
+ * Checks whether a session passes the auth checks (pikkuAuth only) for a
239
+ * given function/agent. Skips pikkuPermission checks since those require
240
+ * request data which isn't available at filter time.
241
+ *
242
+ * @param funcPermissions - The PermissionMetadata[] from function or agent metadata
243
+ * @param session - The user's session
244
+ * @param services - Singleton services
245
+ * @param packageName - Optional package namespace
246
+ * @returns true if the session passes all auth checks (or no auth checks exist)
247
+ */
248
+ export const checkAuthPermissions = async (funcPermissions, session, services, packageName = null) => {
249
+ if (!funcPermissions?.length)
250
+ return true;
251
+ const allPermissions = combinePermissions('agent', `authcheck:${Math.random()}`, {
252
+ funcInheritedPermissions: funcPermissions,
253
+ packageName,
254
+ });
255
+ if (allPermissions.length === 0)
256
+ return true;
257
+ const wire = { session };
258
+ // Extract only pikkuAuth permissions (marked with __pikkuAuth)
259
+ const authPerms = [];
260
+ for (const permission of allPermissions) {
261
+ if (typeof permission === 'function') {
262
+ if (permission.__pikkuAuth) {
263
+ authPerms.push(permission);
264
+ }
265
+ }
266
+ else if (permission && typeof permission === 'object') {
267
+ for (const funcs of Object.values(permission)) {
268
+ const arr = Array.isArray(funcs) ? funcs : [funcs];
269
+ for (const fn of arr) {
270
+ if (typeof fn === 'function' && fn.__pikkuAuth) {
271
+ authPerms.push(fn);
272
+ }
273
+ }
274
+ }
275
+ }
276
+ }
277
+ // No auth permissions = allowed (only data-dependent permissions exist)
278
+ if (authPerms.length === 0)
279
+ return true;
280
+ // All auth permissions must pass
281
+ for (const perm of authPerms) {
282
+ const result = await perm(services, null, wire);
283
+ if (result)
284
+ return true;
285
+ }
286
+ return false;
287
+ };
@@ -23,7 +23,6 @@ export declare const pikkuState: <Type extends keyof PikkuPackageState, Content
23
23
  */
24
24
  export declare const initializePikkuState: (packageName: string) => void;
25
25
  export declare const resetPikkuState: () => void;
26
- export declare const getPikkuMetaDir: (packageName?: string | null) => string | null;
27
26
  export declare const getSingletonServices: () => CoreSingletonServices;
28
27
  export declare const getCreateWireServices: () => CreateWireServices | undefined;
29
28
  /**
@@ -126,8 +126,8 @@ const createEmptyPackageState = () => ({
126
126
  package: {
127
127
  factories: null,
128
128
  singletonServices: null,
129
- metaDir: null,
130
129
  credentialsMeta: null,
130
+ requiredParentServices: null,
131
131
  },
132
132
  });
133
133
  /**
@@ -152,9 +152,6 @@ export const resetPikkuState = () => {
152
152
  if (!getAllPackageStates().has('__main__')) {
153
153
  resetPikkuState();
154
154
  }
155
- export const getPikkuMetaDir = (packageName) => {
156
- return pikkuState(packageName ?? null, 'package', 'metaDir');
157
- };
158
155
  export const getSingletonServices = () => {
159
156
  const services = pikkuState(null, 'package', 'singletonServices');
160
157
  if (!services)
@@ -0,0 +1,10 @@
1
+ import type { JWTService } from './services/jwt-service.js';
2
+ import type { SecretService } from './services/secret-service.js';
3
+ /**
4
+ * Build Authorization headers with JWT-signed session and traceId for
5
+ * pikkuRemoteAuthMiddleware on the receiving end.
6
+ *
7
+ * Used by all deployment services (Kysely, Redis, MongoDB, Lambda, CF, Azure)
8
+ * regardless of transport (HTTP, Lambda Invoke, service bindings).
9
+ */
10
+ export declare function buildRemoteHeaders(jwt: JWTService | undefined, secrets: SecretService | undefined, funcName: string, session?: unknown, traceId?: string): Promise<Record<string, string>>;
package/dist/remote.js ADDED
@@ -0,0 +1,32 @@
1
+ import { encryptJSON } from './crypto-utils.js';
2
+ /**
3
+ * Build Authorization headers with JWT-signed session and traceId for
4
+ * pikkuRemoteAuthMiddleware on the receiving end.
5
+ *
6
+ * Used by all deployment services (Kysely, Redis, MongoDB, Lambda, CF, Azure)
7
+ * regardless of transport (HTTP, Lambda Invoke, service bindings).
8
+ */
9
+ export async function buildRemoteHeaders(jwt, secrets, funcName, session, traceId) {
10
+ const headers = {
11
+ 'content-type': 'application/json',
12
+ ...(traceId && { 'x-request-id': traceId }),
13
+ };
14
+ let secret;
15
+ try {
16
+ secret = await secrets?.getSecret('PIKKU_REMOTE_SECRET');
17
+ }
18
+ catch { }
19
+ if (secret && jwt) {
20
+ const sessionEnc = session
21
+ ? await encryptJSON(secret, { session })
22
+ : undefined;
23
+ const token = await jwt.encode({ value: 5, unit: 'minute' }, {
24
+ aud: 'pikku-remote',
25
+ fn: funcName,
26
+ iat: Math.floor(Date.now() / 1000),
27
+ session: sessionEnc,
28
+ });
29
+ headers.authorization = `Bearer ${token}`;
30
+ }
31
+ return headers;
32
+ }
package/dist/schema.js CHANGED
@@ -67,6 +67,8 @@ const validateAllSchemasLoaded = (logger, schemaService) => {
67
67
  };
68
68
  export const coerceTopLevelDataFromSchema = (schemaName, data, packageName = null) => {
69
69
  const schema = pikkuState(packageName, 'misc', 'schemas').get(schemaName);
70
+ if (!schema?.properties)
71
+ return;
70
72
  for (const key in schema.properties) {
71
73
  const property = schema.properties[key];
72
74
  if (typeof property === 'boolean') {
@@ -15,5 +15,16 @@ export interface DeploymentService {
15
15
  init(): Promise<void>;
16
16
  start(config: DeploymentConfig): Promise<void>;
17
17
  stop(): Promise<void>;
18
- findFunction(name: string): Promise<DeploymentInfo[]>;
18
+ /**
19
+ * Dispatch a remote RPC call to a function.
20
+ * The deployment service owns the full transport:
21
+ * - Resolving the target (endpoint, service binding, etc.)
22
+ * - Session propagation (JWT signing, headers)
23
+ * - The actual network call
24
+ *
25
+ * @param funcName - The function to invoke
26
+ * @param data - Input data for the function
27
+ * @param session - User session to propagate (optional)
28
+ */
29
+ invoke(funcName: string, data: unknown, session?: unknown, traceId?: string): Promise<unknown>;
19
30
  }
@@ -0,0 +1,7 @@
1
+ import type { QueueService, JobOptions } from '../wirings/queue/queue.types.js';
2
+ export declare class InMemoryQueueService implements QueueService {
3
+ readonly supportsResults = false;
4
+ private jobCounter;
5
+ add<T>(queueName: string, data: T, options?: JobOptions): Promise<string>;
6
+ getJob(): Promise<null>;
7
+ }