@pikku/cli 0.12.70 → 0.12.72

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 (98) hide show
  1. package/cli.schema.json +1 -1
  2. package/console-app/assets/{index-BY60UXB6.js → index-Bn7IPpsQ.js} +140 -141
  3. package/console-app/index.html +1 -1
  4. package/dist/.pikku/agent/pikku-agent-types.gen.d.ts +1 -1
  5. package/dist/.pikku/channel/pikku-channel-types.gen.d.ts +1 -1
  6. package/dist/.pikku/channel/pikku-channel-types.gen.js +1 -1
  7. package/dist/.pikku/cli/pikku-cli-channel.js +6 -11
  8. package/dist/.pikku/cli/pikku-cli-client.gen.d.ts +1 -1
  9. package/dist/.pikku/cli/pikku-cli-client.gen.js +1 -1
  10. package/dist/.pikku/cli/pikku-cli-contracts-meta.gen.d.ts +1 -1
  11. package/dist/.pikku/cli/pikku-cli-contracts-meta.gen.js +1 -1
  12. package/dist/.pikku/cli/pikku-cli-types.gen.d.ts +1 -1
  13. package/dist/.pikku/cli/pikku-cli-types.gen.js +1 -1
  14. package/dist/.pikku/cli/pikku-cli-wirings-meta.gen.js +1 -1
  15. package/dist/.pikku/cli/pikku-cli-wirings-meta.gen.json +11 -31
  16. package/dist/.pikku/cli/pikku-cli-wirings.gen.d.ts +1 -1
  17. package/dist/.pikku/cli/pikku-cli-wirings.gen.js +1 -1
  18. package/dist/.pikku/cli/pikku-cli.gen.d.ts +1 -1
  19. package/dist/.pikku/cli/pikku-cli.gen.js +1 -1
  20. package/dist/.pikku/console/pikku-node-types.gen.d.ts +1 -1
  21. package/dist/.pikku/function/pikku-function-types.gen.d.ts +1 -1
  22. package/dist/.pikku/function/pikku-function-types.gen.js +1 -1
  23. package/dist/.pikku/function/pikku-functions-meta.gen.js +1 -1
  24. package/dist/.pikku/function/pikku-functions-meta.gen.json +43 -38
  25. package/dist/.pikku/function/pikku-functions.gen.js +3 -1
  26. package/dist/.pikku/http/pikku-http-types.gen.d.ts +1 -1
  27. package/dist/.pikku/http/pikku-http-types.gen.js +1 -1
  28. package/dist/.pikku/http/pikku-http-wirings-meta.gen.js +1 -1
  29. package/dist/.pikku/http/pikku-http-wirings.gen.d.ts +1 -1
  30. package/dist/.pikku/http/pikku-http-wirings.gen.js +1 -1
  31. package/dist/.pikku/mcp/pikku-mcp-types.gen.d.ts +1 -1
  32. package/dist/.pikku/mcp/pikku-mcp-types.gen.js +1 -1
  33. package/dist/.pikku/pikku-bootstrap.gen.d.ts +1 -1
  34. package/dist/.pikku/pikku-bootstrap.gen.js +1 -1
  35. package/dist/.pikku/pikku-meta-service.gen.d.ts +1 -1
  36. package/dist/.pikku/pikku-meta-service.gen.js +1 -1
  37. package/dist/.pikku/pikku-services.gen.d.ts +1 -1
  38. package/dist/.pikku/pikku-types.gen.d.ts +1 -1
  39. package/dist/.pikku/pikku-types.gen.js +1 -1
  40. package/dist/.pikku/queue/pikku-queue-types.gen.d.ts +1 -1
  41. package/dist/.pikku/queue/pikku-queue-types.gen.js +1 -1
  42. package/dist/.pikku/queue/pikku-queue-workers-wirings-meta.gen.js +1 -1
  43. package/dist/.pikku/queue/pikku-queue-workers-wirings.gen.d.ts +1 -1
  44. package/dist/.pikku/queue/pikku-queue-workers-wirings.gen.js +1 -1
  45. package/dist/.pikku/rpc/pikku-rpc-wirings-meta.internal.gen.js +1 -1
  46. package/dist/.pikku/rpc/pikku-rpc-wirings-meta.internal.gen.json +2 -2
  47. package/dist/.pikku/scheduler/pikku-scheduler-types.gen.d.ts +1 -1
  48. package/dist/.pikku/scheduler/pikku-scheduler-types.gen.js +1 -1
  49. package/dist/.pikku/schemas/register.gen.js +3 -5
  50. package/dist/.pikku/schemas/schemas/PikkuCLIConfig.schema.json +1 -1
  51. package/dist/.pikku/schemas/schemas/PikkuScenarioFunctionsOutput.schema.json +1 -0
  52. package/dist/.pikku/secrets/pikku-secret-types.gen.d.ts +1 -1
  53. package/dist/.pikku/secrets/pikku-secret-types.gen.js +1 -1
  54. package/dist/.pikku/secrets/pikku-secrets.gen.d.ts +1 -1
  55. package/dist/.pikku/secrets/pikku-secrets.gen.js +1 -1
  56. package/dist/.pikku/trigger/pikku-trigger-types.gen.d.ts +1 -1
  57. package/dist/.pikku/trigger/pikku-trigger-types.gen.js +1 -1
  58. package/dist/.pikku/variables/pikku-variable-types.gen.d.ts +1 -1
  59. package/dist/.pikku/variables/pikku-variable-types.gen.js +1 -1
  60. package/dist/.pikku/variables/pikku-variables.gen.d.ts +1 -1
  61. package/dist/.pikku/variables/pikku-variables.gen.js +1 -1
  62. package/dist/.pikku/workflow/meta/allWorkflow.gen.json +8 -2
  63. package/dist/.pikku/workflow/pikku-workflow-types.gen.d.ts +1 -1
  64. package/dist/.pikku/workflow/pikku-workflow-types.gen.js +1 -1
  65. package/dist/.pikku/workflow/pikku-workflow-wirings-meta.gen.js +1 -1
  66. package/dist/.pikku/workflow/pikku-workflow-wirings.gen.js +1 -1
  67. package/dist/bin/pikku-bin.mjs +2 -2
  68. package/dist/src/cli.wiring.js +11 -29
  69. package/dist/src/fabric/fabric-commands.d.ts +3 -3
  70. package/dist/src/fabric/functions/llm-key.function.d.ts +4 -4
  71. package/dist/src/fabric/functions/validate.function.js +54 -15
  72. package/dist/src/functions/commands/enable.d.ts +1 -0
  73. package/dist/src/functions/commands/enable.js +9 -1
  74. package/dist/src/functions/commands/scenario.js +4 -4
  75. package/dist/src/functions/commands/start-coverage.d.ts +1 -1
  76. package/dist/src/functions/commands/start-coverage.js +21 -5
  77. package/dist/src/functions/validate/workspace-validate.js +0 -4
  78. package/dist/src/functions/wirings/auth/pikku-command-auth.js +1 -1
  79. package/dist/src/functions/wirings/auth/serialize-auth-gen.d.ts +1 -16
  80. package/dist/src/functions/wirings/auth/serialize-auth-gen.js +36 -3
  81. package/dist/src/functions/wirings/console/serialize-console-functions.js +0 -6
  82. package/dist/src/functions/wirings/scenarios/pikku-command-scenario-functions.d.ts +1 -0
  83. package/dist/src/functions/wirings/scenarios/pikku-command-scenario-functions.js +25 -0
  84. package/dist/src/functions/wirings/scenarios/serialize-scenario-functions.d.ts +6 -0
  85. package/dist/src/functions/wirings/scenarios/serialize-scenario-functions.js +98 -0
  86. package/dist/src/functions/wirings/workflow/pikku-command-workflow.js +4 -5
  87. package/dist/src/functions/workflows/all.workflow.js +6 -0
  88. package/dist/src/utils/pikku-cli-config.js +3 -0
  89. package/dist/src/utils/precise-coverage-map.d.ts +4 -0
  90. package/dist/src/utils/precise-coverage-map.js +176 -0
  91. package/dist/tsconfig.tsbuildinfo +1 -1
  92. package/package.json +7 -3
  93. package/dist/.pikku/schemas/schemas/PikkuTestsCoverageInput.schema.json +0 -1
  94. package/dist/.pikku/schemas/schemas/PikkuTestsInitInput.schema.json +0 -1
  95. package/dist/src/functions/commands/tests-coverage.d.ts +0 -10
  96. package/dist/src/functions/commands/tests-coverage.js +0 -273
  97. package/dist/src/functions/commands/tests-init.d.ts +0 -7
  98. package/dist/src/functions/commands/tests-init.js +0 -274
@@ -102,21 +102,21 @@ export const scenarioRun = pikkuSessionlessFunc({
102
102
  catch (e) {
103
103
  coverageActive = false;
104
104
  logger.warn(`Coverage disabled — '${rpcName}' failed against '${environment}': ${e?.message ?? e}. ` +
105
- `Is the server running with --coverage and the console addon wired?`);
105
+ `Is the server running with --coverage and "scaffold.scenarios" enabled in pikku.config.json?`);
106
106
  return null;
107
107
  }
108
108
  };
109
109
  for (const flow of selected) {
110
110
  const startedAt = Date.now();
111
111
  if (coverageActive) {
112
- const reset = await invokeCoverage('console:resetLiveCoverage');
112
+ const reset = await invokeCoverage('pikkuScenarioResetLiveCoverage');
113
113
  if (reset && reset.enabled === false) {
114
114
  coverageActive = false;
115
115
  logger.warn(`Coverage disabled — '${environment}' is not collecting (start the server with --coverage).`);
116
116
  }
117
117
  }
118
118
  try {
119
- await coverageActor?.invoke('console:resetStubs', null);
119
+ await coverageActor?.invoke('pikkuScenarioResetStubs', null);
120
120
  }
121
121
  catch { }
122
122
  try {
@@ -148,7 +148,7 @@ export const scenarioRun = pikkuSessionlessFunc({
148
148
  });
149
149
  }
150
150
  if (coverageActive) {
151
- const report = await invokeCoverage('console:takeLiveCoverage');
151
+ const report = await invokeCoverage('pikkuScenarioTakeLiveCoverage');
152
152
  if (report) {
153
153
  scenarioCoverage[flow.name] = report;
154
154
  const covered = report.functions?.filter((f) => f.status === 'covered' || f.status === 'partial');
@@ -1,4 +1,4 @@
1
- import { type CoverageService } from '@pikku/core/services';
1
+ import type { CoverageService } from '@pikku/core/services';
2
2
  interface CoverageLogger {
3
3
  info(message: string): void;
4
4
  warn(message: string): void;
@@ -1,6 +1,22 @@
1
- import { V8CoverageService, IstanbulCoverageService, } from '@pikku/core/services';
1
+ import { V8CoverageService } from '@pikku/core/services/v8-coverage';
2
+ import { IstanbulCoverageService } from '@pikku/core/services/istanbul-coverage';
2
3
  import { registerBunCoverageLoader } from './bun-coverage-loader.js';
4
+ import { mapPreciseCoverage, mapLineHitsToReport, } from '../../utils/precise-coverage-map.js';
3
5
  const isBunRuntime = () => typeof globalThis.Bun !== 'undefined';
6
+ // The source-map-aware span mapping (and its @jridgewell/trace-mapping
7
+ // dependency) lives in the CLI, not @pikku/core — the scaffolded
8
+ // pikkuScenarioTakeLiveCoverage function reaches it through the optional
9
+ // CoverageService.takeReport, which only the CLI-booted service provides.
10
+ const withTakeReport = (service) => {
11
+ service.takeReport = async (functionsMeta) => {
12
+ const snapshot = await service.takeCoverage();
13
+ if (snapshot.kind === 'line-hits') {
14
+ return mapLineHitsToReport(snapshot.lineHits, functionsMeta);
15
+ }
16
+ return mapPreciseCoverage(snapshot.scripts, snapshot.getScriptSource, functionsMeta);
17
+ };
18
+ return service;
19
+ };
4
20
  /**
5
21
  * Starts the coverage backend for `pikku dev --coverage`: V8 precise coverage
6
22
  * on Node, istanbul load-time instrumentation on Bun. Must run before the
@@ -10,14 +26,14 @@ const isBunRuntime = () => typeof globalThis.Bun !== 'undefined';
10
26
  export async function startCoverageService(logger, rootDir) {
11
27
  if (isBunRuntime()) {
12
28
  await registerBunCoverageLoader({ rootDir });
13
- logger.info('Istanbul coverage enabled (Bun) — snapshot via console:takeLiveCoverage, reset via console:resetLiveCoverage');
14
- return new IstanbulCoverageService();
29
+ logger.info('Istanbul coverage enabled (Bun) — snapshot via pikkuScenarioTakeLiveCoverage, reset via pikkuScenarioResetLiveCoverage');
30
+ return withTakeReport(new IstanbulCoverageService());
15
31
  }
16
32
  const coverageService = new V8CoverageService();
17
33
  try {
18
34
  await coverageService.start();
19
- logger.info('V8 precise coverage enabled — snapshot via console:takeLiveCoverage, reset via console:resetLiveCoverage');
20
- return coverageService;
35
+ logger.info('V8 precise coverage enabled — snapshot via pikkuScenarioTakeLiveCoverage, reset via pikkuScenarioResetLiveCoverage');
36
+ return withTakeReport(coverageService);
21
37
  }
22
38
  catch (e) {
23
39
  logger.warn(`V8 precise coverage is not supported on this runtime — continuing without coverage: ${e instanceof Error ? e.message : e}`);
@@ -228,10 +228,6 @@ export async function runWorkspaceValidate(startDir = process.cwd()) {
228
228
  info('config-missing', 'packages/functions/src/config.ts not found', join(fnDir, 'src', 'config.ts'), 'Create src/config.ts and export your workspace config factory');
229
229
  }
230
230
  }
231
- const testsDir = join(fnDir, 'tests');
232
- if (!existsSync(testsDir)) {
233
- info('tests-missing', 'packages/functions/tests/ not found — no function test harness', testsDir, 'Run `pikku tests init` to scaffold the generated function test harness under packages/functions/tests/ (feature files, step defs, and support files)');
234
- }
235
231
  const sdkDir = join(root, 'packages', 'functions-sdk');
236
232
  if (!existsSync(sdkDir)) {
237
233
  info('functions-sdk-missing', 'packages/functions-sdk/ not found — generated RPC client and React Query hooks will not be available', sdkDir, 'Create packages/functions-sdk/ as a workspace with src/pikku/ as the generated output root; point clientFiles.rpcMapDeclarationFile and clientFiles.reactQueryFile there');
@@ -30,7 +30,7 @@ export const pikkuAuth = pikkuSessionlessFunc({
30
30
  // has no OAuth providers — still generates its /auth/* wiring.
31
31
  if (!state.auth.definition)
32
32
  return;
33
- const { wiring, secrets, middleware } = serializeAuthGen(state.auth.definition, state.auth.providers, authFile, typesDeclarationFile, packageMappings ?? {}, state.auth.hasUserSessionMiddleware ?? false);
33
+ const { wiring, secrets, middleware } = serializeAuthGen(state.auth.definition, state.auth.providers, authFile, typesDeclarationFile, packageMappings ?? {}, state.auth.hasUserSessionMiddleware ?? false, Boolean(config.scaffold?.console));
34
34
  // The secrets file sits alongside authFile so re-inspection rediscovers it.
35
35
  // It is kept separate from the wiring file because the CLI forbids Zod
36
36
  // schemas and HTTP wiring (wireHTTPRoutes) in the same file (PKU490).
@@ -18,19 +18,4 @@ export interface AuthGenOutput {
18
18
  * `session.cookieCache` is enabled (stateless path); undefined otherwise. */
19
19
  middleware?: string;
20
20
  }
21
- /**
22
- * Generates the `auth.gen.ts` (HTTP wiring) and `auth-secrets.gen.ts` (schemas +
23
- * secret/variable wiring) files from a `pikkuBetterAuth((services) => betterAuth(...))`
24
- * export.
25
- *
26
- * The wiring file side-effect imports the user's auth file (so `pikkuBetterAuth`
27
- * registers its factory), builds ONE shared sessionless handler that reads the
28
- * resolved `services.auth` and delegates to better-auth's fetch handler, wires a
29
- * catch-all `${basePath}{/*splat}` route per method to it, and registers the
30
- * better-auth session-bridge middleware globally. Provider/plugin metadata for
31
- * the console is emitted separately as `auth-meta.gen.json` (see
32
- * serializeAuthMeta). Because this is normal, statically inspectable HTTP
33
- * wiring, the routes flow through inspection into the deploy manifest (one
34
- * worker for all auth routes).
35
- */
36
- export declare const serializeAuthGen: (definition: AuthDefinition, providers: string[], authFile: string, typesDeclarationFile: string, packageMappings: Record<string, string>, hasUserSessionMiddleware?: boolean) => AuthGenOutput;
21
+ export declare const serializeAuthGen: (definition: AuthDefinition, providers: string[], authFile: string, typesDeclarationFile: string, packageMappings: Record<string, string>, hasUserSessionMiddleware?: boolean, includeConsoleToken?: boolean) => AuthGenOutput;
@@ -33,7 +33,22 @@ function variableSchemaName(name, field) {
33
33
  * wiring, the routes flow through inspection into the deploy manifest (one
34
34
  * worker for all auth routes).
35
35
  */
36
- export const serializeAuthGen = (definition, providers, authFile, typesDeclarationFile, packageMappings, hasUserSessionMiddleware = false) => {
36
+ // External consoles (served from another origin) cannot carry the session
37
+ // cookie, so they authenticate with 'Authorization: Bearer <PIKKU_CONSOLE_TOKEN>'.
38
+ // The expected token resolves through the secrets service per request and the
39
+ // middleware is a no-op while the secret is unset. Emitted into the same
40
+ // addHTTPMiddleware('*') call as the session middleware: the inspector keys
41
+ // route-middleware groups by pattern, so a second '*' registration from another
42
+ // file would silently displace this one in deployed units.
43
+ const consoleTokenMiddlewareLines = () => [
44
+ ` authBearer({`,
45
+ ` token: {`,
46
+ ` secretId: 'PIKKU_CONSOLE_TOKEN',`,
47
+ ` userSession: { userId: 'pikku-console-token' },`,
48
+ ` },`,
49
+ ` }),`,
50
+ ];
51
+ export const serializeAuthGen = (definition, providers, authFile, typesDeclarationFile, packageMappings, hasUserSessionMiddleware = false, includeConsoleToken = false) => {
37
52
  const known = providers.filter((p) => p in PROVIDER_REGISTRY);
38
53
  const basePath = definition.basePath;
39
54
  // Side-effect import of the user's auth file so `pikkuBetterAuth` runs and
@@ -132,6 +147,9 @@ export const serializeAuthGen = (definition, providers, authFile, typesDeclarati
132
147
  emitStatefulSession
133
148
  ? `import { createAuthHandler, betterAuthSession } from '@pikku/better-auth'`
134
149
  : `import { createAuthHandler } from '@pikku/better-auth'`,
150
+ ...(emitStatefulSession && includeConsoleToken
151
+ ? [`import { authBearer } from '@pikku/core/middleware'`]
152
+ : []),
135
153
  `import '${configImportPath}'`,
136
154
  '',
137
155
  // createAuthHandler is called once at module load; the exported handler is a
@@ -148,7 +166,12 @@ export const serializeAuthGen = (definition, providers, authFile, typesDeclarati
148
166
  if (emitStatefulSession) {
149
167
  // Stateful: betterAuthSession calls services.auth(), so it stays here with
150
168
  // the auth.wiring import.
151
- wiring.push(`addHTTPMiddleware('*', [betterAuthSession()])`, '');
169
+ if (includeConsoleToken) {
170
+ wiring.push(`addHTTPMiddleware('*', [`, ` betterAuthSession(),`, ...consoleTokenMiddlewareLines(), `])`, '');
171
+ }
172
+ else {
173
+ wiring.push(`addHTTPMiddleware('*', [betterAuthSession()])`, '');
174
+ }
152
175
  }
153
176
  wiring.push(`wireHTTPRoutes({`, ` routes: {`);
154
177
  // One catch-all route per method. `{/*splat}` matches both the bare basePath
@@ -172,8 +195,18 @@ export const serializeAuthGen = (definition, providers, authFile, typesDeclarati
172
195
  '',
173
196
  `import { addHTTPMiddleware } from '${pikkuTypesImportPath}'`,
174
197
  `import { betterAuthStatelessSession } from '@pikku/better-auth'`,
198
+ ...(includeConsoleToken
199
+ ? [`import { authBearer } from '@pikku/core/middleware'`]
200
+ : []),
175
201
  '',
176
- `addHTTPMiddleware('*', [betterAuthStatelessSession()])`,
202
+ ...(includeConsoleToken
203
+ ? [
204
+ `addHTTPMiddleware('*', [`,
205
+ ` betterAuthStatelessSession(),`,
206
+ ...consoleTokenMiddlewareLines(),
207
+ `])`,
208
+ ]
209
+ : [`addHTTPMiddleware('*', [betterAuthStatelessSession()])`]),
177
210
  '',
178
211
  ];
179
212
  output.middleware = middleware.join('\n');
@@ -94,12 +94,6 @@ export const consoleRoutes = defineHTTPRoutes({
94
94
  sse: true,
95
95
  func: ref('console:streamWorkflowRun'),
96
96
  },
97
- functionTestsStream: {
98
- route: '/function-tests/stream',
99
- method: 'get',
100
- sse: true,
101
- func: ref('console:streamFunctionTests'),
102
- },
103
97
  },
104
98
  })
105
99
 
@@ -0,0 +1 @@
1
+ export declare const pikkuScenarioFunctions: import("#pikku").PikkuFunctionConfig<void, boolean, "rpc" | "session", import("#pikku").PikkuFunctionSessionless<void, boolean, "rpc" | "session", import("#pikku").Services> | import("#pikku").PikkuFunction<void, boolean, "rpc" | "session", import("#pikku").Services>, undefined, undefined>;
@@ -0,0 +1,25 @@
1
+ import { pikkuSessionlessFunc } from '#pikku';
2
+ import { getFileImportRelativePath } from '../../../utils/file-import-path.js';
3
+ import { writeFileInDir } from '../../../utils/file-writer.js';
4
+ import { logCommandInfoAndTime } from '../../../middleware/log-command-info-and-time.js';
5
+ import { serializeScenarioFunctions } from './serialize-scenario-functions.js';
6
+ export const pikkuScenarioFunctions = pikkuSessionlessFunc({
7
+ func: async ({ logger, config, variables }) => {
8
+ const deployCodegenFlag = await variables.get('PIKKU_DEPLOY_CODEGEN');
9
+ if (deployCodegenFlag === '1') {
10
+ return false;
11
+ }
12
+ if (config.scaffold?.scenarios && config.scenariosFunctionsFile) {
13
+ const pathToPikkuTypes = getFileImportRelativePath(config.scenariosFunctionsFile, config.typesDeclarationFile, config.packageMappings);
14
+ await writeFileInDir(logger, config.scenariosFunctionsFile, serializeScenarioFunctions(pathToPikkuTypes, config.scaffold.scenarios === 'auth'));
15
+ return true;
16
+ }
17
+ return false;
18
+ },
19
+ middleware: [
20
+ logCommandInfoAndTime({
21
+ commandStart: 'Generating Scenario functions',
22
+ commandEnd: 'Generated Scenario functions',
23
+ }),
24
+ ],
25
+ });
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Generate the scenario instrumentation functions (`pikku scenario` coverage
3
+ * snapshots and stub-call inspection) into the project scaffold, so scenario
4
+ * runs work against any server without requiring the console addon.
5
+ */
6
+ export declare const serializeScenarioFunctions: (pathToPikkuTypes: string, requireAuth?: boolean) => string;
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Generate the scenario instrumentation functions (`pikku scenario` coverage
3
+ * snapshots and stub-call inspection) into the project scaffold, so scenario
4
+ * runs work against any server without requiring the console addon.
5
+ */
6
+ export const serializeScenarioFunctions = (pathToPikkuTypes, requireAuth = true) => {
7
+ const authFlag = requireAuth ? 'true' : 'false';
8
+ return `/**
9
+ * Auto-generated scenario instrumentation functions
10
+ * Do not edit manually - regenerate with 'npx pikku'
11
+ */
12
+ import { readFile } from 'node:fs/promises'
13
+ import { join } from 'node:path'
14
+ import { pikkuFunc } from '${pathToPikkuTypes}'
15
+ import {
16
+ getStubTracker,
17
+ isTestRun,
18
+ type CoverageFunctionMeta,
19
+ type FunctionCoverageReport,
20
+ type StubCall,
21
+ } from '@pikku/core/services'
22
+
23
+ export const pikkuScenarioTakeLiveCoverage = pikkuFunc<
24
+ null,
25
+ FunctionCoverageReport | null
26
+ >({
27
+ tags: ['pikku'],
28
+ title: 'Take Live Coverage',
29
+ description:
30
+ 'Snapshots the live coverage collected since the server started (or since the last reset) — V8 precise coverage on Node, istanbul instrumentation on Bun — and maps it onto function body spans. Returns null unless the server was started with coverage enabled (pikku dev --coverage).',
31
+ expose: true,
32
+ auth: ${authFlag},
33
+ func: async ({ coverageService, metaService }) => {
34
+ if (!coverageService?.takeReport || !metaService?.basePath) return null
35
+ let functionsMeta: Record<string, CoverageFunctionMeta>
36
+ try {
37
+ const content = await readFile(
38
+ join(
39
+ metaService.basePath,
40
+ 'function',
41
+ 'pikku-functions-meta-verbose.gen.json'
42
+ ),
43
+ 'utf-8'
44
+ )
45
+ functionsMeta = JSON.parse(content)
46
+ } catch {
47
+ return null
48
+ }
49
+ return await coverageService.takeReport(functionsMeta)
50
+ },
51
+ })
52
+
53
+ export const pikkuScenarioResetLiveCoverage = pikkuFunc<
54
+ null,
55
+ { enabled: boolean }
56
+ >({
57
+ tags: ['pikku'],
58
+ title: 'Reset Live Coverage',
59
+ description:
60
+ 'Clears V8 precise-coverage call counts so the next takeLiveCoverage snapshot is attributable to a single scenario run. Reports enabled: false when the server was not started with coverage enabled.',
61
+ expose: true,
62
+ auth: ${authFlag},
63
+ func: async ({ coverageService }) => {
64
+ if (!coverageService) return { enabled: false }
65
+ await coverageService.reset()
66
+ return { enabled: true }
67
+ },
68
+ })
69
+
70
+ export const pikkuScenarioResetStubs = pikkuFunc<null, { enabled: boolean }>({
71
+ tags: ['pikku'],
72
+ title: 'Reset Stubs',
73
+ description:
74
+ 'Clears recorded stub calls so the next getStubCalls result is attributable to a single scenario run. Reports enabled: false when the server was not started in test mode.',
75
+ expose: true,
76
+ auth: ${authFlag},
77
+ func: async () => {
78
+ getStubTracker().reset()
79
+ return { enabled: isTestRun() }
80
+ },
81
+ })
82
+
83
+ export const pikkuScenarioGetStubCalls = pikkuFunc<
84
+ { service?: string },
85
+ StubCall[]
86
+ >({
87
+ tags: ['pikku'],
88
+ title: 'Get Stub Calls',
89
+ description:
90
+ 'Returns calls recorded against stubbed/spied services (via the stub()/spy() core utils). Empty unless the server records service calls (pikku dev --test).',
91
+ expose: true,
92
+ auth: ${authFlag},
93
+ func: async (_services, data) => {
94
+ return getStubTracker().getCalls(data?.service ?? undefined)
95
+ },
96
+ })
97
+ `;
98
+ };
@@ -10,7 +10,7 @@ import { serializeWorkflowBootstrapMap } from './serialize-workflow-bootstrap-ma
10
10
  import { serializeWorkflowMeta } from './serialize-workflow-meta.js';
11
11
  import { getFileImportRelativePath } from '../../../utils/file-import-path.js';
12
12
  import { stripVerboseFields, hasVerboseFields, } from '../../../utils/strip-verbose-meta.js';
13
- import { join, dirname } from 'path';
13
+ import { join } from 'path';
14
14
  export const pikkuWorkflow = pikkuSessionlessFunc({
15
15
  func: async ({ logger, config, getInspectorState }, input) => {
16
16
  const bootstrap = input?.bootstrap === true;
@@ -67,10 +67,9 @@ export const pikkuWorkflow = pikkuSessionlessFunc({
67
67
  if (scenarioActors && Object.keys(scenarioActors).length > 0) {
68
68
  const agentMapImportPath = getFileImportRelativePath(config.scenarioActorsFile, config.agentMapDeclarationFile, packageMappings);
69
69
  await writeFileInDir(logger, config.scenarioActorsFile, serializeScenarioActors(scenarioActors, agentMapImportPath));
70
- // JSON twin for the runtime meta service (console personas view). Lives
71
- // next to workflow/meta but NOT inside it — getWorkflowMeta() treats
72
- // every workflow/meta/*.gen.json as a workflow.
73
- await writeFileInDir(logger, join(dirname(config.scenarioActorsFile), 'scenario-actors.gen.json'), JSON.stringify(scenarioActors, null, 2));
70
+ // Fixed path getScenarioActorsMeta() reads; kept out of workflow/meta,
71
+ // which getWorkflowMeta() globs as workflows.
72
+ await writeFileInDir(logger, join(config.outDir, 'workflow', 'scenario-actors.gen.json'), JSON.stringify(scenarioActors, null, 2));
74
73
  }
75
74
  await writeFileInDir(logger, workflowMapDeclarationFile, bootstrap
76
75
  ? serializeWorkflowBootstrapMap(workflows.meta, workflows.graphMeta)
@@ -11,6 +11,11 @@ const scaffoldFiles = (config) => {
11
11
  file: config.consoleFunctionsFile,
12
12
  generator: 'pikkuConsoleFunctions',
13
13
  });
14
+ if (config.scaffold?.scenarios && config.scenariosFunctionsFile)
15
+ files.push({
16
+ file: config.scenariosFunctionsFile,
17
+ generator: 'pikkuScenarioFunctions',
18
+ });
14
19
  if (config.scaffold?.agent && config.publicAgentFile)
15
20
  files.push({
16
21
  file: config.publicAgentFile,
@@ -126,6 +131,7 @@ export const allWorkflow = pikkuWorkflowComplexFunc({
126
131
  await Promise.all([
127
132
  workflow.do('Public RPC', 'pikkuPublicRPC', null),
128
133
  workflow.do('Console functions', 'pikkuConsoleFunctions', null),
134
+ workflow.do('Scenario functions', 'pikkuScenarioFunctions', null),
129
135
  workflow.do('Events scaffold', 'pikkuEventsScaffold', null),
130
136
  workflow.do('Emails', 'pikkuEmails', null),
131
137
  workflow.do('Secret definition types', 'pikkuSecretDefinitionTypes', null),
@@ -221,6 +221,9 @@ const _getPikkuCLIConfig = async (logger, configFile = undefined, requiredFields
221
221
  if (result.scaffold?.console && !result.consoleFunctionsFile) {
222
222
  result.consoleFunctionsFile = join(resolvedScaffoldDir, 'console.gen.ts');
223
223
  }
224
+ if (result.scaffold?.scenarios && !result.scenariosFunctionsFile) {
225
+ result.scenariosFunctionsFile = join(resolvedScaffoldDir, 'scenarios.gen.ts');
226
+ }
224
227
  if (!result.authFile) {
225
228
  result.authFile = join(resolvedScaffoldDir, 'auth.gen.ts');
226
229
  }
@@ -0,0 +1,4 @@
1
+ import type { CoverageFunctionMeta, FunctionCoverageReport, ScriptCoverage as ScriptCoverageInput } from '@pikku/core/services';
2
+ export type { ScriptCoverageInput };
3
+ export declare function mapPreciseCoverage(scripts: ScriptCoverageInput[], getScriptSource: (scriptId: string) => Promise<string>, functionsMeta: Record<string, CoverageFunctionMeta>): Promise<FunctionCoverageReport>;
4
+ export declare function mapLineHitsToReport(lineHits: Map<string, Map<number, number>>, functionsMeta: Record<string, CoverageFunctionMeta>): FunctionCoverageReport;
@@ -0,0 +1,176 @@
1
+ // Offsets are mapped through the inline source map rather than line-based
2
+ // statement maps: esbuild emits the whole module on one generated line, which
3
+ // would collapse every statement onto line 1.
4
+ import { fileURLToPath } from 'node:url';
5
+ import { TraceMap, originalPositionFor } from '@jridgewell/trace-mapping';
6
+ const INLINE_SOURCE_MAP = /\/\/# sourceMappingURL=data:application\/json[^,]*;base64,([A-Za-z0-9+/=]+)/;
7
+ function extractInlineSourceMap(source) {
8
+ const match = source.match(INLINE_SOURCE_MAP);
9
+ if (!match)
10
+ return undefined;
11
+ try {
12
+ return JSON.parse(Buffer.from(match[1], 'base64').toString('utf-8'));
13
+ }
14
+ catch {
15
+ return undefined;
16
+ }
17
+ }
18
+ function computeLineStarts(source) {
19
+ const starts = [0];
20
+ for (let i = 0; i < source.length; i++) {
21
+ if (source[i] === '\n')
22
+ starts.push(i + 1);
23
+ }
24
+ return starts;
25
+ }
26
+ function offsetToGeneratedPosition(offset, lineStarts) {
27
+ let low = 0;
28
+ let high = lineStarts.length - 1;
29
+ while (low < high) {
30
+ const mid = (low + high + 1) >> 1;
31
+ if (lineStarts[mid] <= offset)
32
+ low = mid;
33
+ else
34
+ high = mid - 1;
35
+ }
36
+ return { line: low + 1, column: offset - lineStarts[low] };
37
+ }
38
+ function normalizeSourcePath(source) {
39
+ if (source.startsWith('file://')) {
40
+ try {
41
+ return fileURLToPath(source);
42
+ }
43
+ catch {
44
+ return source;
45
+ }
46
+ }
47
+ return source;
48
+ }
49
+ async function scriptToLineCoverage(script, getScriptSource, lineHits) {
50
+ let scriptPath;
51
+ try {
52
+ scriptPath = fileURLToPath(script.url);
53
+ }
54
+ catch {
55
+ return;
56
+ }
57
+ let source;
58
+ try {
59
+ source = await getScriptSource(script.scriptId);
60
+ }
61
+ catch {
62
+ return;
63
+ }
64
+ const sourcemap = extractInlineSourceMap(source);
65
+ let tracer;
66
+ if (sourcemap) {
67
+ try {
68
+ tracer = new TraceMap(sourcemap);
69
+ }
70
+ catch {
71
+ tracer = undefined;
72
+ }
73
+ }
74
+ const lineStarts = computeLineStarts(source);
75
+ const mapOffset = (offset) => {
76
+ const generated = offsetToGeneratedPosition(offset, lineStarts);
77
+ if (!tracer)
78
+ return { file: scriptPath, line: generated.line };
79
+ const original = originalPositionFor(tracer, generated);
80
+ if (original.source == null || original.line == null)
81
+ return undefined;
82
+ const sourceIndex = tracer.sources.indexOf(original.source);
83
+ const resolved = sourceIndex >= 0
84
+ ? (tracer.resolvedSources[sourceIndex] ?? original.source)
85
+ : original.source;
86
+ return { file: normalizeSourcePath(resolved), line: original.line };
87
+ };
88
+ const setHits = (file, from, to, count) => {
89
+ let hits = lineHits.get(file);
90
+ if (!hits) {
91
+ hits = new Map();
92
+ lineHits.set(file, hits);
93
+ }
94
+ for (let line = from; line <= to; line++) {
95
+ hits.set(line, count);
96
+ }
97
+ };
98
+ for (const fn of script.functions) {
99
+ // Inner ranges overwrite the outer count (V8 override semantics).
100
+ for (const range of fn.ranges) {
101
+ const start = mapOffset(range.startOffset);
102
+ const end = mapOffset(Math.max(range.startOffset, range.endOffset - 1));
103
+ if (!start && !end)
104
+ continue;
105
+ const file = (start ?? end).file;
106
+ const from = start?.line ?? end.line;
107
+ const to = end && end.file === file ? Math.max(end.line, from) : from;
108
+ setHits(file, from, to, range.count);
109
+ }
110
+ }
111
+ }
112
+ export async function mapPreciseCoverage(scripts, getScriptSource, functionsMeta) {
113
+ const lineHits = new Map();
114
+ for (const script of scripts) {
115
+ await scriptToLineCoverage(script, getScriptSource, lineHits);
116
+ }
117
+ return mapLineHitsToReport(lineHits, functionsMeta);
118
+ }
119
+ export function mapLineHitsToReport(lineHits, functionsMeta) {
120
+ const functions = Object.values(functionsMeta)
121
+ .filter((m) => m.sourceFile && !m.sourceFile.endsWith('.gen.ts'))
122
+ .map((m) => {
123
+ const hits = lineHits.get(m.bodySourceFile ?? m.sourceFile);
124
+ const covered = [];
125
+ const missed = [];
126
+ if (hits && m.bodyStart !== undefined && m.bodyEnd !== undefined) {
127
+ for (const [line, count] of hits) {
128
+ if (line < m.bodyStart || line > m.bodyEnd)
129
+ continue;
130
+ if (count > 0)
131
+ covered.push(line);
132
+ else
133
+ missed.push(line);
134
+ }
135
+ }
136
+ const total = covered.length + missed.length;
137
+ const ratio = total ? covered.length / total : 0;
138
+ const status = total === 0
139
+ ? 'unknown'
140
+ : covered.length === 0
141
+ ? 'uncovered'
142
+ : missed.length === 0
143
+ ? 'covered'
144
+ : 'partial';
145
+ return {
146
+ name: m.name,
147
+ sourceFile: m.sourceFile,
148
+ exposed: m.expose !== false,
149
+ description: m.description ?? null,
150
+ coveredLines: covered.length,
151
+ totalLines: total,
152
+ missedLines: missed.sort((a, b) => a - b),
153
+ ratio: Number(ratio.toFixed(3)),
154
+ status,
155
+ };
156
+ })
157
+ .sort((a, b) => a.ratio - b.ratio || a.name.localeCompare(b.name));
158
+ const summary = {
159
+ total: functions.length,
160
+ covered: 0,
161
+ partial: 0,
162
+ uncovered: 0,
163
+ unknown: 0,
164
+ overallRatio: 0,
165
+ };
166
+ for (const f of functions)
167
+ summary[f.status]++;
168
+ summary.overallRatio = functions.length
169
+ ? Number((functions.reduce((a, f) => a + f.ratio, 0) / functions.length).toFixed(3))
170
+ : 0;
171
+ return {
172
+ generatedAt: new Date().toISOString(),
173
+ summary,
174
+ functions,
175
+ };
176
+ }