@jondotsoy/pika 0.1.1

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 (83) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -0
  3. package/lib/esm/auth/dto/connection.d.ts +43 -0
  4. package/lib/esm/auth/dto/connection.js +16 -0
  5. package/lib/esm/auth/index.d.ts +10 -0
  6. package/lib/esm/auth/index.js +64 -0
  7. package/lib/esm/cli/__samples__/parent-child-script.d.ts +1 -0
  8. package/lib/esm/cli/__samples__/parent-child-script.js +9 -0
  9. package/lib/esm/cli/cli-event-payload.d.ts +53 -0
  10. package/lib/esm/cli/cli-event-payload.js +32 -0
  11. package/lib/esm/cli/index.d.ts +2 -0
  12. package/lib/esm/cli/index.js +167 -0
  13. package/lib/esm/cli/utils/create-server.d.ts +20 -0
  14. package/lib/esm/cli/utils/create-server.js +70 -0
  15. package/lib/esm/flow/__samples__/credentials-job.d.ts +1 -0
  16. package/lib/esm/flow/__samples__/credentials-job.js +9 -0
  17. package/lib/esm/flow/__samples__/only-app.d.ts +1 -0
  18. package/lib/esm/flow/__samples__/only-app.js +4 -0
  19. package/lib/esm/flow/__samples__/parent-child-jobs.d.ts +1 -0
  20. package/lib/esm/flow/__samples__/parent-child-jobs.js +10 -0
  21. package/lib/esm/flow/__samples__/parent-with-subjobs.d.ts +1 -0
  22. package/lib/esm/flow/__samples__/parent-with-subjobs.js +9 -0
  23. package/lib/esm/flow/__samples__/wait-job.d.ts +1 -0
  24. package/lib/esm/flow/__samples__/wait-job.js +6 -0
  25. package/lib/esm/flow/__samples__/zod-invalid-job.d.ts +1 -0
  26. package/lib/esm/flow/__samples__/zod-invalid-job.js +4 -0
  27. package/lib/esm/flow/__samples__/zod-validation-job.d.ts +1 -0
  28. package/lib/esm/flow/__samples__/zod-validation-job.js +6 -0
  29. package/lib/esm/flow/configs/env-configs.d.ts +37 -0
  30. package/lib/esm/flow/configs/env-configs.js +59 -0
  31. package/lib/esm/flow/constants/run-mode.d.ts +5 -0
  32. package/lib/esm/flow/constants/run-mode.js +6 -0
  33. package/lib/esm/flow/context-reflects/cli-http-reflect.d.ts +9 -0
  34. package/lib/esm/flow/context-reflects/cli-http-reflect.js +55 -0
  35. package/lib/esm/flow/context-reflects/dsn-reflect.d.ts +29 -0
  36. package/lib/esm/flow/context-reflects/dsn-reflect.js +181 -0
  37. package/lib/esm/flow/context-reflects/file-context-reflect.d.ts +22 -0
  38. package/lib/esm/flow/context-reflects/file-context-reflect.js +47 -0
  39. package/lib/esm/flow/context.d.ts +43 -0
  40. package/lib/esm/flow/context.js +104 -0
  41. package/lib/esm/flow/current.d.ts +4 -0
  42. package/lib/esm/flow/current.js +1 -0
  43. package/lib/esm/flow/dto/cb-app.d.ts +2 -0
  44. package/lib/esm/flow/dto/cb-app.js +1 -0
  45. package/lib/esm/flow/dto/job-id.d.ts +1 -0
  46. package/lib/esm/flow/dto/job-id.js +1 -0
  47. package/lib/esm/flow/dto/job.d.ts +18 -0
  48. package/lib/esm/flow/dto/job.js +9 -0
  49. package/lib/esm/flow/dto/manifest.d.ts +5 -0
  50. package/lib/esm/flow/dto/manifest.js +1 -0
  51. package/lib/esm/flow/index.d.ts +26 -0
  52. package/lib/esm/flow/index.js +46 -0
  53. package/lib/esm/flow/loader.d.ts +1 -0
  54. package/lib/esm/flow/loader.js +227 -0
  55. package/lib/esm/flow/util/json-rpc-transporter.d.ts +80 -0
  56. package/lib/esm/flow/util/json-rpc-transporter.js +175 -0
  57. package/lib/esm/flow/utils/bytes.d.ts +29 -0
  58. package/lib/esm/flow/utils/bytes.js +32 -0
  59. package/lib/esm/flow/utils/event-manager.d.ts +11 -0
  60. package/lib/esm/flow/utils/event-manager.js +41 -0
  61. package/lib/esm/flow/utils/file.d.ts +17 -0
  62. package/lib/esm/flow/utils/file.js +52 -0
  63. package/lib/esm/flow/utils/observable-set.d.ts +9 -0
  64. package/lib/esm/flow/utils/observable-set.js +31 -0
  65. package/lib/esm/flow/utils/queue.d.ts +32 -0
  66. package/lib/esm/flow/utils/queue.js +86 -0
  67. package/lib/esm/flow/worker_ctx.d.ts +5 -0
  68. package/lib/esm/flow/worker_ctx.js +2 -0
  69. package/lib/esm/http/index.d.ts +32 -0
  70. package/lib/esm/http/index.js +54 -0
  71. package/lib/esm/telemetry/metrics/gateway.d.ts +2 -0
  72. package/lib/esm/telemetry/metrics/gateway.js +6 -0
  73. package/lib/esm/telemetry/metrics/job-gauges.d.ts +13 -0
  74. package/lib/esm/telemetry/metrics/job-gauges.js +39 -0
  75. package/lib/esm/telemetry/metrics/job-store.d.ts +3 -0
  76. package/lib/esm/telemetry/metrics/job-store.js +31 -0
  77. package/lib/esm/telemetry/metrics/push.d.ts +1 -0
  78. package/lib/esm/telemetry/metrics/push.js +4 -0
  79. package/lib/esm/telemetry/metrics/registry.d.ts +2 -0
  80. package/lib/esm/telemetry/metrics/registry.js +2 -0
  81. package/lib/esm/telemetry/metrics/telemetry-url.d.ts +1 -0
  82. package/lib/esm/telemetry/metrics/telemetry-url.js +1 -0
  83. package/package.json +55 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jonathan Delgado hi@jon.soy https://jon.soy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,50 @@
1
+ # @jondotsoy/pika
2
+
3
+ A job execution framework with event-driven context management. Register and run named jobs with typed inputs, persistent YAML state, and automatic retries.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @jondotsoy/pika
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ Run your script directly with `npx`:
14
+
15
+ ```bash
16
+ npx @jondotsoy/pika script.js
17
+ ```
18
+
19
+ Or use the loader manually:
20
+
21
+ ```bash
22
+ node --import @jondotsoy/pika/loader script.js
23
+ ```
24
+
25
+ Define and execute jobs using the `app()` function:
26
+
27
+ ```javascript
28
+ import { app } from "@jondotsoy/pika";
29
+
30
+ const greet = app("greet", {
31
+ input: { name: z.string() },
32
+ handler: async ({ name }) => {
33
+ console.log(`Hello, ${name}!`);
34
+ },
35
+ });
36
+
37
+ greet("job-1", { name: "World" });
38
+ ```
39
+
40
+ ## Features
41
+
42
+ - **Persistent state** — job state is automatically saved to a YAML manifest and survives process restarts
43
+ - **Typed inputs** — input definitions provide TypeScript inference for job parameters
44
+ - **Automatic retries** — jobs retry on failure up to `maxRetries` (default: 3)
45
+ - **Parent-child jobs** — async local storage tracks job context across async boundaries
46
+ - **Event-driven** — subscribe to lifecycle events or consume them as an async iterable
47
+
48
+ ## License
49
+
50
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,43 @@
1
+ export declare enum TypeConnection {
2
+ api_key = "API key",
3
+ basic_auth = "Basic auth",
4
+ oauth_2_0 = "OAuth 2.0"
5
+ }
6
+ export declare enum Placement {
7
+ headers = "headers",
8
+ query = "query"
9
+ }
10
+ export type APIKEYConnection = {
11
+ type: TypeConnection.api_key;
12
+ key: string;
13
+ placement?: Placement;
14
+ parameterName?: string;
15
+ prefix?: string;
16
+ sufix?: string;
17
+ };
18
+ export type BasicAuthConnection = {
19
+ type: TypeConnection.basic_auth;
20
+ username: string;
21
+ password: string;
22
+ };
23
+ export declare enum OAuth2_0FlowType {
24
+ code = "code",
25
+ implicit = "implicit"
26
+ }
27
+ export type OAuth2_0Connection = {
28
+ type: TypeConnection.oauth_2_0;
29
+ flowType: OAuth2_0FlowType;
30
+ authorizeURI: string;
31
+ tokenURI: string;
32
+ scope: string[];
33
+ clientID: string;
34
+ clientSecret: string;
35
+ authorizeParameters?: Record<string, string>;
36
+ accessTokenParameters?: Record<string, string>;
37
+ refreshTokenParameters?: Record<string, string>;
38
+ customHeaders?: Record<string, string>;
39
+ placement: Placement;
40
+ tokenPrefix?: string;
41
+ tokenSufix?: string;
42
+ };
43
+ export type Connection = APIKEYConnection | BasicAuthConnection | OAuth2_0Connection;
@@ -0,0 +1,16 @@
1
+ export var TypeConnection;
2
+ (function (TypeConnection) {
3
+ TypeConnection["api_key"] = "API key";
4
+ TypeConnection["basic_auth"] = "Basic auth";
5
+ TypeConnection["oauth_2_0"] = "OAuth 2.0";
6
+ })(TypeConnection || (TypeConnection = {}));
7
+ export var Placement;
8
+ (function (Placement) {
9
+ Placement["headers"] = "headers";
10
+ Placement["query"] = "query";
11
+ })(Placement || (Placement = {}));
12
+ export var OAuth2_0FlowType;
13
+ (function (OAuth2_0FlowType) {
14
+ OAuth2_0FlowType["code"] = "code";
15
+ OAuth2_0FlowType["implicit"] = "implicit";
16
+ })(OAuth2_0FlowType || (OAuth2_0FlowType = {}));
@@ -0,0 +1,10 @@
1
+ import { TypeConnection, Placement } from "./dto/connection.js";
2
+ export { TypeConnection, Placement, OAuth2_0FlowType, } from "./dto/connection.js";
3
+ export type { Connection, APIKEYConnection, BasicAuthConnection, OAuth2_0Connection, } from "./dto/connection.js";
4
+ export type Credentials = {
5
+ type: TypeConnection;
6
+ placement?: Placement;
7
+ parameterName?: string;
8
+ value(): Promise<string>;
9
+ };
10
+ export declare function getCredentials(name: string): Promise<Credentials>;
@@ -0,0 +1,64 @@
1
+ import { TypeConnection, } from "./dto/connection.js";
2
+ export { TypeConnection, Placement, OAuth2_0FlowType, } from "./dto/connection.js";
3
+ function toCredentials(conn) {
4
+ if (conn.type === TypeConnection.api_key) {
5
+ return {
6
+ type: conn.type,
7
+ placement: conn.placement,
8
+ parameterName: conn.parameterName,
9
+ value: async () => `${conn.prefix ?? ""}${conn.key}${conn.sufix ?? ""}`,
10
+ };
11
+ }
12
+ if (conn.type === TypeConnection.basic_auth) {
13
+ return {
14
+ type: conn.type,
15
+ value: async () => `Basic ${btoa(`${conn.username}:${conn.password}`)}`,
16
+ };
17
+ }
18
+ // oauth_2_0
19
+ return {
20
+ type: conn.type,
21
+ placement: conn.placement,
22
+ value: async () => {
23
+ const body = new URLSearchParams({
24
+ grant_type: "client_credentials",
25
+ client_id: conn.clientID,
26
+ client_secret: conn.clientSecret,
27
+ scope: conn.scope.join(" "),
28
+ ...conn.accessTokenParameters,
29
+ });
30
+ const headers = {
31
+ "Content-Type": "application/x-www-form-urlencoded",
32
+ ...conn.customHeaders,
33
+ };
34
+ const res = await fetch(conn.tokenURI, { method: "POST", headers, body });
35
+ const data = await res.json();
36
+ const prefix = conn.tokenPrefix ?? "Bearer ";
37
+ const sufix = conn.tokenSufix ?? "";
38
+ // @ts-ignore
39
+ return `${prefix}${data.access_token}${sufix}`;
40
+ },
41
+ };
42
+ }
43
+ async function decryptCredentials(encrypted, publicKey) {
44
+ const keyBytes = Buffer.from(publicKey, "base64");
45
+ const encryptedBytes = Buffer.from(encrypted, "base64");
46
+ const iv = encryptedBytes.subarray(0, 12);
47
+ const ciphertext = encryptedBytes.subarray(12);
48
+ const cryptoKey = await crypto.subtle.importKey("raw", keyBytes, { name: "AES-GCM" }, false, ["decrypt"]);
49
+ const decrypted = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, cryptoKey, ciphertext);
50
+ return new TextDecoder().decode(decrypted);
51
+ }
52
+ export async function getCredentials(name) {
53
+ const raw = process.env.PIKA_CONTEXT_CREDENTIALS;
54
+ if (!raw)
55
+ throw new Error("PIKA_CONTEXT_CREDENTIALS is not set");
56
+ const publicKey = process.env.PIKA_CONTEXT_CREDENTIALS_PUBLIC_KEY;
57
+ const json = publicKey ? await decryptCredentials(raw, publicKey) : raw;
58
+ const store = JSON.parse(json);
59
+ const conn = store[name];
60
+ if (!conn)
61
+ throw new Error(`Connection "${name}" not found`);
62
+ // @ts-ignore
63
+ return toCredentials(conn);
64
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,9 @@
1
+ import { app } from "@jondotsoy/pika";
2
+ const child = app("child-job", {}, async () => {
3
+ await new Promise((r) => setTimeout(r, 20));
4
+ });
5
+ const parent = app("parent-job", {}, async () => {
6
+ child("child-1", {});
7
+ child("child-2", {});
8
+ });
9
+ parent("run-1", {});
@@ -0,0 +1,53 @@
1
+ import { z } from "zod";
2
+ export declare const CliEventPayloadSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
3
+ event: z.ZodLiteral<"job_created">;
4
+ jobId: z.ZodString;
5
+ job: z.ZodObject<{
6
+ appId: z.ZodString;
7
+ parentJobId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
8
+ startedAt: z.ZodOptional<z.ZodNullable<z.ZodString>>;
9
+ completedAt: z.ZodOptional<z.ZodNullable<z.ZodString>>;
10
+ }, z.core.$strip>;
11
+ }, z.core.$strip>, z.ZodObject<{
12
+ event: z.ZodLiteral<"job_started">;
13
+ jobId: z.ZodString;
14
+ job: z.ZodObject<{
15
+ appId: z.ZodString;
16
+ parentJobId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
17
+ startedAt: z.ZodOptional<z.ZodNullable<z.ZodString>>;
18
+ completedAt: z.ZodOptional<z.ZodNullable<z.ZodString>>;
19
+ }, z.core.$strip>;
20
+ }, z.core.$strip>, z.ZodObject<{
21
+ event: z.ZodLiteral<"job_done">;
22
+ jobId: z.ZodString;
23
+ job: z.ZodObject<{
24
+ appId: z.ZodString;
25
+ parentJobId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
26
+ startedAt: z.ZodOptional<z.ZodNullable<z.ZodString>>;
27
+ completedAt: z.ZodOptional<z.ZodNullable<z.ZodString>>;
28
+ }, z.core.$strip>;
29
+ }, z.core.$strip>, z.ZodObject<{
30
+ event: z.ZodLiteral<"job_error">;
31
+ jobId: z.ZodString;
32
+ job: z.ZodObject<{
33
+ appId: z.ZodString;
34
+ parentJobId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
35
+ startedAt: z.ZodOptional<z.ZodNullable<z.ZodString>>;
36
+ completedAt: z.ZodOptional<z.ZodNullable<z.ZodString>>;
37
+ }, z.core.$strip>;
38
+ error: z.ZodObject<{
39
+ name: z.ZodString;
40
+ message: z.ZodString;
41
+ }, z.core.$strip>;
42
+ }, z.core.$strip>, z.ZodObject<{
43
+ event: z.ZodLiteral<"job_retry">;
44
+ jobId: z.ZodString;
45
+ job: z.ZodObject<{
46
+ appId: z.ZodString;
47
+ parentJobId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
48
+ startedAt: z.ZodOptional<z.ZodNullable<z.ZodString>>;
49
+ completedAt: z.ZodOptional<z.ZodNullable<z.ZodString>>;
50
+ }, z.core.$strip>;
51
+ retryCount: z.ZodNumber;
52
+ }, z.core.$strip>], "event">;
53
+ export type CliEventPayload = z.infer<typeof CliEventPayloadSchema>;
@@ -0,0 +1,32 @@
1
+ import { z } from "zod";
2
+ const JobSchema = z.object({
3
+ appId: z.string(),
4
+ parentJobId: z.string().nullable().optional(),
5
+ startedAt: z.string().nullable().optional(),
6
+ completedAt: z.string().nullable().optional(),
7
+ });
8
+ export const CliEventPayloadSchema = z.discriminatedUnion("event", [
9
+ z.object({
10
+ event: z.literal("job_created"),
11
+ jobId: z.string(),
12
+ job: JobSchema,
13
+ }),
14
+ z.object({
15
+ event: z.literal("job_started"),
16
+ jobId: z.string(),
17
+ job: JobSchema,
18
+ }),
19
+ z.object({ event: z.literal("job_done"), jobId: z.string(), job: JobSchema }),
20
+ z.object({
21
+ event: z.literal("job_error"),
22
+ jobId: z.string(),
23
+ job: JobSchema,
24
+ error: z.object({ name: z.string(), message: z.string() }),
25
+ }),
26
+ z.object({
27
+ event: z.literal("job_retry"),
28
+ jobId: z.string(),
29
+ job: JobSchema,
30
+ retryCount: z.number(),
31
+ }),
32
+ ]);
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,167 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from "node:child_process";
3
+ import { serve } from "./utils/create-server.js";
4
+ import { CliEventPayloadSchema, } from "./cli-event-payload.js";
5
+ import { flags, argument } from "@jondotsoy/flags";
6
+ var Engine;
7
+ (function (Engine) {
8
+ Engine[Engine["BUN"] = 0] = "BUN";
9
+ Engine[Engine["NODE"] = 1] = "NODE";
10
+ // DENO
11
+ })(Engine || (Engine = {}));
12
+ function detectEngine() {
13
+ const ARG0 = process.argv0.toLowerCase();
14
+ const enginesMatch = [
15
+ [Engine.BUN, ARG0.endsWith("bun") || ARG0.endsWith("bunx")],
16
+ [Engine.NODE, ARG0.endsWith("node") || ARG0.endsWith("node.exe")],
17
+ // [Engine.DENO, ARG0.endsWith("deno") || ARG0.endsWith("deno.exe")]
18
+ ];
19
+ const engine = enginesMatch.find(([_, match]) => match)?.[0] ?? null;
20
+ if (engine === null) {
21
+ throw new Error(`Unsupported JavaScript engine: ${ARG0}`);
22
+ }
23
+ return { argv0: process.argv0, engine };
24
+ }
25
+ const parser = flags({
26
+ script: argument().string().describe("Script to run"),
27
+ }).program("pika");
28
+ function parseArgs() {
29
+ const [ok, error, output] = parser.safeParse(process.argv.slice(2));
30
+ if (!ok) {
31
+ console.error(parser.formatError(error));
32
+ process.exit(1);
33
+ }
34
+ const script = output.script;
35
+ if (!script) {
36
+ console.error("No script provided. Usage: pika <script>");
37
+ process.exit(1);
38
+ }
39
+ return { script };
40
+ }
41
+ const jobs = new Map();
42
+ function applyEvent(payload) {
43
+ const { jobId, job } = payload;
44
+ const existing = jobs.get(jobId);
45
+ let status = existing?.status ?? "running";
46
+ if (payload.event === "job_done")
47
+ status = "done";
48
+ else if (payload.event === "job_error")
49
+ status = "error";
50
+ else if (payload.event === "job_started" ||
51
+ payload.event === "job_created" ||
52
+ payload.event === "job_retry")
53
+ status = "running";
54
+ jobs.set(jobId, {
55
+ jobId,
56
+ parentJobId: job.parentJobId ?? null,
57
+ appId: job.appId,
58
+ status,
59
+ startedAt: job.startedAt ? new Date(job.startedAt) : null,
60
+ completedAt: job.completedAt ? new Date(job.completedAt) : null,
61
+ });
62
+ }
63
+ // --- Terminal renderer ---
64
+ const isTTY = process.stdout.isTTY === true;
65
+ let prevLineCount = 0;
66
+ function renderJobs() {
67
+ const now = Date.now();
68
+ const lines = [];
69
+ // Group children by parentJobId
70
+ const childrenOf = new Map();
71
+ const roots = [];
72
+ for (const entry of jobs.values()) {
73
+ if (entry.parentJobId === null) {
74
+ roots.push(entry);
75
+ }
76
+ else {
77
+ const siblings = childrenOf.get(entry.parentJobId) ?? [];
78
+ siblings.push(entry);
79
+ childrenOf.set(entry.parentJobId, siblings);
80
+ }
81
+ }
82
+ function formatEntry(entry, indent) {
83
+ const prefix = " ".repeat(indent);
84
+ const { jobId, status, startedAt, completedAt } = entry;
85
+ let durationSec = 0;
86
+ if (startedAt) {
87
+ const endMs = completedAt ? completedAt.getTime() : now;
88
+ durationSec = Math.round((endMs - startedAt.getTime()) / 1000);
89
+ }
90
+ lines.push(`${prefix}${jobId}: ${status} ${durationSec}s`);
91
+ const children = childrenOf.get(jobId) ?? [];
92
+ for (const child of children) {
93
+ formatEntry(child, indent + 1);
94
+ }
95
+ }
96
+ for (const root of roots) {
97
+ formatEntry(root, 0);
98
+ }
99
+ // Erase previous render then write new
100
+ if (prevLineCount > 0) {
101
+ process.stdout.write(`\x1B[${prevLineCount}A\x1B[0J`);
102
+ }
103
+ if (lines.length > 0) {
104
+ process.stdout.write(lines.join("\n") + "\n");
105
+ }
106
+ prevLineCount = lines.length;
107
+ }
108
+ // --- Inspector HTTP server ---
109
+ async function startInspector(onEvent) {
110
+ const key = crypto.randomUUID();
111
+ const server = await serve({
112
+ port: 0,
113
+ routes: {
114
+ [`/inspector/${key}`]: {
115
+ POST: async (request) => {
116
+ try {
117
+ onEvent(CliEventPayloadSchema.parse(await request.json()));
118
+ }
119
+ catch { }
120
+ return new Response(null, { status: 204 });
121
+ },
122
+ },
123
+ },
124
+ });
125
+ const inspectorUrl = `${server.url}inspector/${key}`;
126
+ return { inspectorUrl, stop: server.close };
127
+ }
128
+ // --- Main ---
129
+ async function main() {
130
+ const { argv0, engine } = detectEngine();
131
+ const { script } = parseArgs();
132
+ const { inspectorUrl, stop } = await startInspector((payload) => {
133
+ applyEvent(payload);
134
+ if (isTTY) {
135
+ try {
136
+ renderJobs();
137
+ }
138
+ catch {
139
+ // Non-TTY or unsupported terminal — skip rendering
140
+ }
141
+ }
142
+ });
143
+ const args = {
144
+ [Engine.BUN]: ["run", "--import", "@jondotsoy/pika/loader", script],
145
+ [Engine.NODE]: ["--import", "@jondotsoy/pika/loader", script],
146
+ };
147
+ const child = spawn(argv0, args[engine], {
148
+ stdio: "inherit",
149
+ env: {
150
+ ...process.env,
151
+ PIKA_CLI_INSPECTOR_URL: inspectorUrl,
152
+ },
153
+ });
154
+ await new Promise((resolve) => {
155
+ child.on("exit", (code) => {
156
+ stop();
157
+ if (code !== null && code !== 0) {
158
+ process.exitCode = code;
159
+ }
160
+ resolve();
161
+ });
162
+ });
163
+ }
164
+ main().catch((error) => {
165
+ console.error("Error:", error);
166
+ process.exit(1);
167
+ });
@@ -0,0 +1,20 @@
1
+ type RouteHandler = (request: Request) => Response | Promise<Response>;
2
+ type RouteMethod = {
3
+ GET?: RouteHandler;
4
+ POST?: RouteHandler;
5
+ PUT?: RouteHandler;
6
+ PATCH?: RouteHandler;
7
+ DELETE?: RouteHandler;
8
+ };
9
+ type Routes = Record<string, RouteMethod>;
10
+ type ServeOptions = {
11
+ port?: number;
12
+ hostname?: string;
13
+ routes: Routes;
14
+ };
15
+ type Server = {
16
+ url: URL;
17
+ close: () => void;
18
+ };
19
+ export declare function serve(options: ServeOptions): Promise<Server>;
20
+ export {};
@@ -0,0 +1,70 @@
1
+ import { createServer, } from "node:http";
2
+ async function toNodeResponse(res, webResponse) {
3
+ const headers = {};
4
+ webResponse.headers.forEach((value, key) => {
5
+ headers[key] = value;
6
+ });
7
+ res.writeHead(webResponse.status, headers);
8
+ const body = await webResponse.arrayBuffer();
9
+ res.end(Buffer.from(body));
10
+ }
11
+ async function toWebRequest(req) {
12
+ const chunks = [];
13
+ for await (const chunk of req) {
14
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
15
+ }
16
+ const body = chunks.length > 0 ? Buffer.concat(chunks) : null;
17
+ const url = `http://localhost${req.url ?? "/"}`;
18
+ const headers = new Headers();
19
+ for (const [key, value] of Object.entries(req.headers)) {
20
+ if (value !== undefined) {
21
+ if (Array.isArray(value)) {
22
+ for (const v of value)
23
+ headers.append(key, v);
24
+ }
25
+ else {
26
+ headers.set(key, value);
27
+ }
28
+ }
29
+ }
30
+ return new Request(url, {
31
+ method: req.method ?? "GET",
32
+ headers,
33
+ body: body && body.length > 0 ? body : null,
34
+ });
35
+ }
36
+ export function serve(options) {
37
+ const { port = 0, hostname = "localhost", routes } = options;
38
+ return new Promise((resolve, reject) => {
39
+ const server = createServer(async (req, res) => {
40
+ const path = req.url?.split("?")[0] ?? "/";
41
+ const method = req.method ?? "GET";
42
+ const routeMethods = routes[path];
43
+ const handler = routeMethods?.[method];
44
+ if (!handler) {
45
+ res.writeHead(404).end();
46
+ return;
47
+ }
48
+ try {
49
+ const webRequest = await toWebRequest(req);
50
+ const webResponse = await handler(webRequest);
51
+ await toNodeResponse(res, webResponse);
52
+ }
53
+ catch {
54
+ res.writeHead(500).end();
55
+ }
56
+ });
57
+ server.listen(port, hostname, () => {
58
+ const addr = server.address();
59
+ const host = addr.address.includes(":")
60
+ ? `[${addr.address}]`
61
+ : addr.address;
62
+ const url = new URL(`http://${host}:${addr.port}`);
63
+ resolve({
64
+ url,
65
+ close: () => server.close(),
66
+ });
67
+ });
68
+ server.on("error", reject);
69
+ });
70
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,9 @@
1
+ import { app } from "../index.js";
2
+ import { http } from "../../http/index.js";
3
+ import { getCredentials } from "../../auth/index.js";
4
+ const job = app("credentials-job", {}, async () => {
5
+ const credentials = await getCredentials("mykey");
6
+ const { body } = await http(process.env.MOCK_SERVER_URL, { credentials });
7
+ console.log(`job completed authorized=${body.authorized}`);
8
+ });
9
+ job("run-1", {});
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ import { app } from "../index.js";
2
+ app("wait-job", {}, async () => {
3
+ console.log("job completed");
4
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,10 @@
1
+ import { app } from "../index.js";
2
+ const childJob = app("child-app", {}, async () => {
3
+ console.log("child job done");
4
+ });
5
+ const mainJob = app("main-app", {}, async () => {
6
+ console.log("main job running");
7
+ childJob("child-1", {});
8
+ childJob("child-2", {});
9
+ });
10
+ mainJob("main-run", {});
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,9 @@
1
+ import { app } from "../index.js";
2
+ const subJob = app("sub-job", {}, async () => {
3
+ console.log("subjob completed");
4
+ });
5
+ const parentJob = app("parent-job", {}, async () => {
6
+ subJob("sub-1", {});
7
+ subJob("sub-2", {});
8
+ });
9
+ parentJob("parent-run", {});
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,6 @@
1
+ import { app } from "../index.js";
2
+ const job = app("wait-job", {}, async () => {
3
+ await new Promise((resolve) => setTimeout(resolve, 300));
4
+ console.log("job completed");
5
+ });
6
+ job("run-1", {});
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ import { app } from "../index.js";
2
+ import { z } from "zod";
3
+ const job = app("zod-invalid-job", { name: z.string(), age: z.number() }, async () => { });
4
+ job("run-1", { name: "Bob", age: "not-a-number" });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,6 @@
1
+ import { app } from "../index.js";
2
+ import { z } from "zod";
3
+ const job = app("zod-validation-job", { name: z.string().min(1), age: z.number().int().positive() }, async (params) => {
4
+ console.log(`job completed name=${params.name} age=${params.age}`);
5
+ });
6
+ job("run-1", { name: "Alice", age: 30 });