@alienplatform/sdk 3.3.46 → 3.3.47

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.
package/dist/index.d.ts CHANGED
@@ -26,6 +26,7 @@
26
26
  *
27
27
  * @packageDocumentation
28
28
  */
29
+ export { storageEventFromMessage } from "./storage-events.js";
29
30
  export type { CronEvent, QueueBatchEvent, QueueDelivery, QueueDeliveryOutcome, QueueMessage, QueueMessageEvent, ScheduledEvent, StandardSchema, StandardSchemaOutput, StorageEvent, StorageEventType, WorkerCommandContext, } from "./worker-runtime/registry.js";
30
31
  export { command, onCronEvent, onQueueBatch, onQueueMessage, onStorageEvent, waitUntil, } from "./worker-runtime/registry.js";
31
32
  export type { CommandFrame, Container, CreateSandboxOptions, JobError, JobExit, JobPoll, Kv, Postgres, PostgresConnection, PostgresSslMode, Queue, ResolvedSandbox, RunCommandOptions, Sandbox, SandboxInstance, Storage, Vault, } from "@alienplatform/bindings";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAOH,YAAY,EACV,SAAS,EACT,eAAe,EACf,aAAa,EACb,oBAAoB,EACpB,YAAY,EACZ,iBAAiB,EACjB,cAAc,EACd,cAAc,EACd,oBAAoB,EACpB,YAAY,EACZ,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,8BAA8B,CAAA;AACrC,OAAO,EACL,OAAO,EACP,WAAW,EACX,YAAY,EACZ,cAAc,EACd,cAAc,EACd,SAAS,GACV,MAAM,8BAA8B,CAAA;AAMrC,YAAY,EACV,YAAY,EACZ,SAAS,EACT,oBAAoB,EACpB,QAAQ,EACR,OAAO,EACP,OAAO,EACP,EAAE,EACF,QAAQ,EACR,kBAAkB,EAClB,eAAe,EACf,KAAK,EACL,eAAe,EACf,iBAAiB,EACjB,OAAO,EACP,eAAe,EACf,OAAO,EACP,KAAK,GACN,MAAM,yBAAyB,CAAA;AAChC,OAAO,EAAE,SAAS,EAAE,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,yBAAyB,CAAA;AAMjG,YAAY,EACV,SAAS,EACT,YAAY,EACZ,OAAO,EACP,gBAAgB,EAChB,0BAA0B,EAC1B,iBAAiB,EACjB,oBAAoB,GACrB,MAAM,2BAA2B,CAAA;AAClC,OAAO,EACL,EAAE,EACF,EAAE,EACF,eAAe,EACf,mBAAmB,EACnB,cAAc,EACd,cAAc,GACf,MAAM,2BAA2B,CAAA;AAMlC,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAA;AAC7E,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAA;AACnE,OAAO,EAAE,UAAU,EAAE,oBAAoB,EAAE,yBAAyB,EAAE,MAAM,qBAAqB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAA;AAO7D,YAAY,EACV,SAAS,EACT,eAAe,EACf,aAAa,EACb,oBAAoB,EACpB,YAAY,EACZ,iBAAiB,EACjB,cAAc,EACd,cAAc,EACd,oBAAoB,EACpB,YAAY,EACZ,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,8BAA8B,CAAA;AACrC,OAAO,EACL,OAAO,EACP,WAAW,EACX,YAAY,EACZ,cAAc,EACd,cAAc,EACd,SAAS,GACV,MAAM,8BAA8B,CAAA;AAMrC,YAAY,EACV,YAAY,EACZ,SAAS,EACT,oBAAoB,EACpB,QAAQ,EACR,OAAO,EACP,OAAO,EACP,EAAE,EACF,QAAQ,EACR,kBAAkB,EAClB,eAAe,EACf,KAAK,EACL,eAAe,EACf,iBAAiB,EACjB,OAAO,EACP,eAAe,EACf,OAAO,EACP,KAAK,GACN,MAAM,yBAAyB,CAAA;AAChC,OAAO,EAAE,SAAS,EAAE,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,yBAAyB,CAAA;AAMjG,YAAY,EACV,SAAS,EACT,YAAY,EACZ,OAAO,EACP,gBAAgB,EAChB,0BAA0B,EAC1B,iBAAiB,EACjB,oBAAoB,GACrB,MAAM,2BAA2B,CAAA;AAClC,OAAO,EACL,EAAE,EACF,EAAE,EACF,eAAe,EACf,mBAAmB,EACnB,cAAc,EACd,cAAc,GACf,MAAM,2BAA2B,CAAA;AAMlC,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAA;AAC7E,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAA;AACnE,OAAO,EAAE,UAAU,EAAE,oBAAoB,EAAE,yBAAyB,EAAE,MAAM,qBAAqB,CAAA"}
package/dist/index.js CHANGED
@@ -1,4 +1,27 @@
1
- import { d as onQueueBatch, f as onQueueMessage, g as waitUntil, n as BindingNotFoundError, p as onStorageEvent, r as InvalidBindingConfigError, s as command, t as AlienError, u as onCronEvent } from "./dist.js";
1
+ import { _ as defineError, a as onQueueBatch, g as StorageEventSchema, h as InvalidBindingConfigError, i as onCronEvent, m as BindingNotFoundError, o as onQueueMessage, p as AlienError, s as onStorageEvent, t as command, u as waitUntil, v as object, y as string } from "./registry.js";
2
2
  import { BindingNotConfiguredError, container, kv, postgres, queue, sandbox, storage, vault } from "@alienplatform/bindings";
3
3
  import { Ai, AiTransportError, AiUpstreamError, ai, getAiConnection, isExternalAiBinding, parseAiBinding, startAiGateway } from "@alienplatform/ai-gateway";
4
- export { Ai, AiTransportError, AiUpstreamError, AlienError, BindingNotConfiguredError, BindingNotFoundError, InvalidBindingConfigError, ai, command, container, getAiConnection, isExternalAiBinding, kv, onCronEvent, onQueueBatch, onQueueMessage, onStorageEvent, parseAiBinding, postgres, queue, sandbox, startAiGateway, storage, vault, waitUntil };
4
+ // src/storage-events.ts
5
+ /** A queue payload cannot be decoded as the portable storage event. */
6
+ const InvalidStorageEventMessage = defineError({
7
+ code: "INVALID_STORAGE_EVENT_MESSAGE",
8
+ context: object({ messageId: string().optional() }),
9
+ message: ({ messageId }) => messageId === void 0 ? "Queue payload is not a valid StorageEvent" : `Queue message '${messageId}' is not a valid StorageEvent`,
10
+ retryable: false,
11
+ internal: false,
12
+ httpStatusCode: 400
13
+ });
14
+ /**
15
+ * Decode a storage notification from either a Worker queue delivery or `queue.receive()`.
16
+ * Validates the canonical event schema, including the timestamp and optional object size.
17
+ * This does not acknowledge the message; acknowledge only after processing succeeds.
18
+ */
19
+ async function storageEventFromMessage(message) {
20
+ try {
21
+ const payload = typeof message.payload === "string" ? JSON.parse(message.payload) : message.payload;
22
+ return StorageEventSchema.parse(payload);
23
+ } catch (error) {
24
+ throw (await AlienError.from(error)).withContext(InvalidStorageEventMessage.create({ messageId: message.id }));
25
+ }
26
+ }
27
+ export { Ai, AiTransportError, AiUpstreamError, AlienError, BindingNotConfiguredError, BindingNotFoundError, InvalidBindingConfigError, ai, command, container, getAiConnection, isExternalAiBinding, kv, onCronEvent, onQueueBatch, onQueueMessage, onStorageEvent, parseAiBinding, postgres, queue, sandbox, startAiGateway, storage, storageEventFromMessage, vault, waitUntil };
@@ -1,189 +1,3 @@
1
- // src/worker-runtime/system-log.ts
2
- /**
3
- * Private wire marker understood by alien-worker-runtime.
4
- *
5
- * The runtime removes this marker before forwarding the message and, when the
6
- * log path supports structured metadata, records `alien.system=true`.
7
- */
8
- const SYSTEM_LOG_PREFIX = "ALIEN_SYSTEM";
9
- function logSystemError(message, ...args) {
10
- console.error(`${SYSTEM_LOG_PREFIX}${message}`, ...args);
11
- }
12
- function logSystemWarn(message, ...args) {
13
- console.warn(`${SYSTEM_LOG_PREFIX}${message}`, ...args);
14
- }
15
- // src/worker-runtime/registry.ts
16
- const REGISTRY_KEY = Symbol.for("@alienplatform/sdk#worker-runtime-registry");
17
- function registry$1() {
18
- const holder = globalThis;
19
- let state = holder[REGISTRY_KEY];
20
- if (!state) {
21
- state = {
22
- commands: /* @__PURE__ */ new Map(),
23
- eventHandlers: /* @__PURE__ */ new Map(),
24
- waitUntilTasks: /* @__PURE__ */ new Map(),
25
- counters: {
26
- handler: 0,
27
- task: 0
28
- }
29
- };
30
- holder[REGISTRY_KEY] = state;
31
- }
32
- return state;
33
- }
34
- function command(name, schemaOrHandler, validatedHandler) {
35
- const schema = validatedHandler === void 0 ? void 0 : schemaOrHandler;
36
- const handler = validatedHandler ?? schemaOrHandler;
37
- registry$1().commands.set(name, {
38
- name,
39
- handler: async (params, context) => {
40
- if (schema === void 0) return await handler(params, context);
41
- const result = await schema["~standard"].validate(params);
42
- if (result.issues !== void 0) {
43
- const details = result.issues.map((issue) => issue.message).join("; ");
44
- throw new Error(`Command input failed validation${details ? `: ${details}` : ""}`);
45
- }
46
- return await handler(result.value, context);
47
- }
48
- });
49
- }
50
- /** Get all registered commands. @internal */
51
- function getCommands() {
52
- return registry$1().commands;
53
- }
54
- /** Execute a registered command by name. @internal */
55
- async function runCommand(name, params, context) {
56
- const commands = registry$1().commands;
57
- const cmd = commands.get(name);
58
- if (!cmd) throw new Error(`Unknown command: ${name}. Available: ${[...commands.keys()].join(", ")}`);
59
- return await cmd.handler(params, context);
60
- }
61
- /**
62
- * Register a storage event handler.
63
- *
64
- * @param bucket - Bucket name (or `"*"` for all buckets)
65
- * @param handler - Handler function for storage events
66
- * @param options - Handler options
67
- * @returns Unsubscribe function
68
- */
69
- function onStorageEvent(bucket, handler, options) {
70
- const state = registry$1();
71
- const id = `storage-${++state.counters.handler}`;
72
- state.eventHandlers.set(id, {
73
- registration: {
74
- id,
75
- type: "storage",
76
- source: bucket,
77
- prefix: options?.prefix
78
- },
79
- handler
80
- });
81
- return () => {
82
- state.eventHandlers.delete(id);
83
- };
84
- }
85
- /**
86
- * Register a cron/scheduled event handler.
87
- *
88
- * @param scheduleName - Schedule name (or `"*"` for all schedules)
89
- * @param handler - Handler function for scheduled events
90
- * @returns Unsubscribe function
91
- */
92
- function onCronEvent(scheduleName, handler) {
93
- const state = registry$1();
94
- const id = `cron-${++state.counters.handler}`;
95
- state.eventHandlers.set(id, {
96
- registration: {
97
- id,
98
- type: "cron",
99
- source: scheduleName
100
- },
101
- handler
102
- });
103
- return () => {
104
- state.eventHandlers.delete(id);
105
- };
106
- }
107
- /**
108
- * Register a queue message handler.
109
- *
110
- * @param queueName - Queue name (or `"*"` for all queues)
111
- * @param handler - Handler function for queue messages
112
- * @returns Unsubscribe function
113
- */
114
- function onQueueMessage(queueName, handler) {
115
- const state = registry$1();
116
- const id = `queue-${++state.counters.handler}`;
117
- state.eventHandlers.set(id, {
118
- registration: {
119
- id,
120
- type: "queue",
121
- source: queueName
122
- },
123
- handler
124
- });
125
- return () => {
126
- state.eventHandlers.delete(id);
127
- };
128
- }
129
- /** Register an opt-in batch handler. Batches may contain fewer than the configured maximum. */
130
- function onQueueBatch(queueName, handler) {
131
- const state = registry$1();
132
- const id = `queue-batch-${++state.counters.handler}`;
133
- state.eventHandlers.set(id, {
134
- registration: {
135
- id,
136
- type: "queueBatch",
137
- source: queueName
138
- },
139
- handler
140
- });
141
- return () => {
142
- state.eventHandlers.delete(id);
143
- };
144
- }
145
- /** Get all registered event handlers. @internal */
146
- function getEventHandlers() {
147
- return registry$1().eventHandlers;
148
- }
149
- /**
150
- * Register a background task to continue after the response.
151
- *
152
- * The runtime waits for all registered tasks to complete before shutting down.
153
- * This is the protocol-only registrar: it tracks the promise and (inside a
154
- * running Worker) notifies the runtime via the installed hook. The gRPC drain
155
- * coordination lives in {@link runWorker}.
156
- *
157
- * @param promise - The promise to track
158
- */
159
- function waitUntil(promise) {
160
- const state = registry$1();
161
- const id = `task-${++state.counters.task}`;
162
- const tracker = {
163
- id,
164
- promise,
165
- registeredAt: /* @__PURE__ */ new Date(),
166
- completed: false
167
- };
168
- state.waitUntilTasks.set(id, tracker);
169
- promise.then(() => {
170
- tracker.completed = true;
171
- }).catch((error) => {
172
- tracker.completed = true;
173
- tracker.error = error instanceof Error ? error : new Error(String(error));
174
- }).finally(() => {
175
- state.waitUntilTasks.delete(id);
176
- });
177
- try {
178
- state.onTaskRegistered?.(tracker);
179
- } catch (error) {
180
- logSystemError("[alien:wait-until] onTaskRegistered hook failed:", error);
181
- }
182
- }
183
- /** Install the runtime's task-registered hook. @internal */
184
- function setOnTaskRegistered(hook) {
185
- registry$1().onTaskRegistered = hook;
186
- }
187
1
  // ../../node_modules/.pnpm/zod@4.5.2/node_modules/zod/v4/core/util.js
188
2
  function getEnumValues(entries) {
189
3
  const numericValues = Object.values(entries).filter((v) => typeof v === "number");
@@ -3153,10 +2967,10 @@ var $ZodRegistry = class {
3153
2967
  return this._map.has(schema);
3154
2968
  }
3155
2969
  };
3156
- function registry() {
2970
+ function registry$1() {
3157
2971
  return new $ZodRegistry();
3158
2972
  }
3159
- (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());
2973
+ (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry$1());
3160
2974
  const globalRegistry = globalThis.__zod_globalRegistry;
3161
2975
  // ../../node_modules/.pnpm/zod@4.5.2/node_modules/zod/v4/core/api.js
3162
2976
  // @__NO_SIDE_EFFECTS__
@@ -5983,6 +5797,7 @@ const StackResourceStateSchema = object({
5983
5797
  get "error"() {
5984
5798
  return union([AlienErrorSchema, _null()]).optional();
5985
5799
  },
5800
+ "externalBinding": optional(boolean().describe("Whether this resource was adopted from an external binding instead of provisioned.\nThe binding may exist only where the adopting executor ran (a Helm value or a\nchart-created database), so the record carries it: deleting the resource releases it\nand never touches what the binding points at.")),
5986
5801
  "lastFailedState": optional(any().describe("Stores the controller state that failed, used for manual retry operations.\nThis allows resuming from the exact point where the failure occurred.\nStored as JSON to make the struct serializable and movable to alien-core.")),
5987
5802
  get "lifecycle"() {
5988
5803
  return union([ResourceLifecycleSchema, _null()]).optional();
@@ -6724,6 +6539,14 @@ object({
6724
6539
  * Generated by Kubb (https://kubb.dev/).
6725
6540
  * Do not edit manually.
6726
6541
  */
6542
+ /**
6543
+ * @description An IAM condition accepts one string or a list of alternative string values.
6544
+ */
6545
+ const AwsConditionValueSchema = union([array(string()), string()]).describe("An IAM condition accepts one string or a list of alternative string values.");
6546
+ /**
6547
+ * Generated by Kubb (https://kubb.dev/).
6548
+ * Do not edit manually.
6549
+ */
6727
6550
  const AwsCustomCertificateConfigSchema = object({ "certificateArn": string() });
6728
6551
  /**
6729
6552
  * Generated by Kubb (https://kubb.dev/).
@@ -7231,12 +7054,12 @@ const AwsPermissionEffectSchema = _enum(["Allow", "Deny"]);
7231
7054
  */
7232
7055
  const BindingConfigurationAwsBindingSpecSchema = object({
7233
7056
  "resource": optional(object({
7234
- "condition": object({}).catchall(object({}).catchall(string())).describe("Optional condition for additional filtering (rare)").nullish(),
7057
+ "condition": object({}).catchall(object({}).catchall(lazy(() => AwsConditionValueSchema).describe("An IAM condition accepts one string or a list of alternative string values."))).describe("Optional condition for additional filtering (rare)").nullish(),
7235
7058
  "notResources": optional(array(string()).describe("ARN patterns rendered as IAM `NotResource`, in place of `resources`. Its one use is a\ntag-on-create grant whose implied check AWS authorizes against no resource; the build\nrefuses it anywhere else.")),
7236
7059
  "resources": array(string()).describe("Resource ARNs to bind to")
7237
7060
  }).describe("AWS-specific binding specification")),
7238
7061
  "stack": optional(object({
7239
- "condition": object({}).catchall(object({}).catchall(string())).describe("Optional condition for additional filtering (rare)").nullish(),
7062
+ "condition": object({}).catchall(object({}).catchall(lazy(() => AwsConditionValueSchema).describe("An IAM condition accepts one string or a list of alternative string values."))).describe("Optional condition for additional filtering (rare)").nullish(),
7240
7063
  "notResources": optional(array(string()).describe("ARN patterns rendered as IAM `NotResource`, in place of `resources`. Its one use is a\ntag-on-create grant whose implied check AWS authorizes against no resource; the build\nrefuses it anywhere else.")),
7241
7064
  "resources": array(string()).describe("Resource ARNs to bind to")
7242
7065
  }).describe("AWS-specific binding specification"))
@@ -7328,6 +7151,8 @@ const AwsRemoteStackManagementHeartbeatDataSchema = object({
7328
7151
  });
7329
7152
  object({
7330
7153
  "managementPermissionsApplied": boolean().describe("Whether the management inline policy was attached by the generated stack."),
7154
+ "permissionsBoundaryArn": string().describe("Setup-owned permissions boundary for roles written by management. Absent in older setups.").nullish(),
7155
+ "permissionsBoundaryDocument": optional(any().describe("Installed boundary document with setup template parameters resolved. Required with its ARN.")),
7331
7156
  "roleArn": string().describe("Cross-account management role ARN."),
7332
7157
  "roleName": string().describe("Cross-account management role name.")
7333
7158
  }).describe("AWS RemoteStackManagement ImportData.");
@@ -12989,6 +12814,31 @@ const StorageEventSchema = object({
12989
12814
  "versionId": string().describe("Optional version or sequencer identifier for the event or object state.").nullish()
12990
12815
  }).describe("Represents an event triggered by an action in an object storage service.\n\nThis struct provides a generic representation for events from services like\nAWS S3, Google Cloud Storage (GCS), and Azure Blob Storage.");
12991
12816
  array(lazy(() => StorageEventSchema).describe("Represents an event triggered by an action in an object storage service.\n\nThis struct provides a generic representation for events from services like\nAWS S3, Google Cloud Storage (GCS), and Azure Blob Storage.")).describe("A wrapper type for a list of storage events.");
12817
+ /**
12818
+ * Generated by Kubb (https://kubb.dev/).
12819
+ * Do not edit manually.
12820
+ */
12821
+ /**
12822
+ * @description Object events that can be delivered to a queue.
12823
+ */
12824
+ const StorageNotificationEventSchema = _enum(["created"]).describe("Object events that can be delivered to a queue.");
12825
+ /**
12826
+ * Generated by Kubb (https://kubb.dev/).
12827
+ * Do not edit manually.
12828
+ */
12829
+ /**
12830
+ * @description Delivers matching object events to a queue in the same stack.\nRules on one Storage must not overlap: no object key may match two of them.\nDelivery is at least once, so consumers must tolerate duplicates.
12831
+ */
12832
+ const StorageNotificationSchema = object({
12833
+ get "events"() {
12834
+ return array(StorageNotificationEventSchema.describe("Object events that can be delivered to a queue.")).describe("Events to deliver. Defaults to object creation; v1 supports only `created`.").optional();
12835
+ },
12836
+ "prefix": string().describe("Literal object key prefix, non-empty and at most 512 UTF-8 bytes when set.").nullish(),
12837
+ get "queue"() {
12838
+ return ResourceRefSchema.describe("Reference to a resource by its stable id and resource type.");
12839
+ },
12840
+ "suffix": string().describe("Literal object key suffix, non-empty and at most 128 UTF-8 bytes when set.").nullish()
12841
+ }).describe("Delivers matching object events to a queue in the same stack.\nRules on one Storage must not overlap: no object key may match two of them.\nDelivery is at least once, so consumers must tolerate duplicates.");
12992
12842
  object({ "bucketName": string().describe("The globally unique name of the bucket.") }).describe("Outputs generated by a successfully provisioned Storage bucket.");
12993
12843
  object({
12994
12844
  "corsAllowedOrigins": optional(array(string()).describe("Browser origins allowed to read objects through signed URLs.\n\nWhen non-empty, providers configure CORS for `GET` and `HEAD` requests.\nAn origin of `*` is appropriate for private buckets whose signed URLs\nare bearer credentials and do not use browser cookies.\nDefault: `[]` (CORS disabled).")),
@@ -12999,6 +12849,9 @@ object({
12999
12849
  get "lifecycleRules"() {
13000
12850
  return array(LifecycleRuleSchema.describe("Defines a rule for managing the lifecycle of objects within a storage bucket.")).describe("List of rules for automatic object management (e.g., expiration).\nDefault: `[]` (empty list)").optional();
13001
12851
  },
12852
+ get "notifications"() {
12853
+ return array(StorageNotificationSchema.describe("Delivers matching object events to a queue in the same stack.\nRules on one Storage must not overlap: no object key may match two of them.\nDelivery is at least once, so consumers must tolerate duplicates.")).max(10).describe("Object notification rules delivered into queues (at most 10).\nOmitted when empty to preserve existing serialized configurations and setup digests.").optional();
12854
+ },
13002
12855
  "publicRead": optional(boolean().describe("Allows public read access to objects without authentication.\nDefault: `false`")),
13003
12856
  "versioning": optional(boolean().describe("Enables object versioning.\nDefault: `false`"))
13004
12857
  }).describe("Represents an object storage bucket.");
@@ -13726,4 +13579,198 @@ defineError({
13726
13579
  internal: false,
13727
13580
  httpStatusCode: 400
13728
13581
  });
13729
- export { logSystemError as _, object as a, getCommands as c, onQueueBatch as d, onQueueMessage as f, waitUntil as g, setOnTaskRegistered as h, defineError as i, getEventHandlers as l, runCommand as m, BindingNotFoundError as n, string as o, onStorageEvent as p, InvalidBindingConfigError as r, command as s, AlienError as t, onCronEvent as u, logSystemWarn as v };
13582
+ defineError({
13583
+ code: "INVALID_STORAGE_NOTIFICATION",
13584
+ context: object({ reason: string() }),
13585
+ message: ({ reason }) => `Invalid storage notification: ${reason}`,
13586
+ retryable: false,
13587
+ internal: false,
13588
+ httpStatusCode: 400
13589
+ });
13590
+ // src/worker-runtime/system-log.ts
13591
+ /**
13592
+ * Private wire marker understood by alien-worker-runtime.
13593
+ *
13594
+ * The runtime removes this marker before forwarding the message and, when the
13595
+ * log path supports structured metadata, records `alien.system=true`.
13596
+ */
13597
+ const SYSTEM_LOG_PREFIX = "ALIEN_SYSTEM";
13598
+ function logSystemError(message, ...args) {
13599
+ console.error(`${SYSTEM_LOG_PREFIX}${message}`, ...args);
13600
+ }
13601
+ function logSystemWarn(message, ...args) {
13602
+ console.warn(`${SYSTEM_LOG_PREFIX}${message}`, ...args);
13603
+ }
13604
+ // src/worker-runtime/registry.ts
13605
+ const REGISTRY_KEY = Symbol.for("@alienplatform/sdk#worker-runtime-registry");
13606
+ function registry() {
13607
+ const holder = globalThis;
13608
+ let state = holder[REGISTRY_KEY];
13609
+ if (!state) {
13610
+ state = {
13611
+ commands: /* @__PURE__ */ new Map(),
13612
+ eventHandlers: /* @__PURE__ */ new Map(),
13613
+ waitUntilTasks: /* @__PURE__ */ new Map(),
13614
+ counters: {
13615
+ handler: 0,
13616
+ task: 0
13617
+ }
13618
+ };
13619
+ holder[REGISTRY_KEY] = state;
13620
+ }
13621
+ return state;
13622
+ }
13623
+ function command(name, schemaOrHandler, validatedHandler) {
13624
+ const schema = validatedHandler === void 0 ? void 0 : schemaOrHandler;
13625
+ const handler = validatedHandler ?? schemaOrHandler;
13626
+ registry().commands.set(name, {
13627
+ name,
13628
+ handler: async (params, context) => {
13629
+ if (schema === void 0) return await handler(params, context);
13630
+ const result = await schema["~standard"].validate(params);
13631
+ if (result.issues !== void 0) {
13632
+ const details = result.issues.map((issue) => issue.message).join("; ");
13633
+ throw new Error(`Command input failed validation${details ? `: ${details}` : ""}`);
13634
+ }
13635
+ return await handler(result.value, context);
13636
+ }
13637
+ });
13638
+ }
13639
+ /** Get all registered commands. @internal */
13640
+ function getCommands() {
13641
+ return registry().commands;
13642
+ }
13643
+ /** Execute a registered command by name. @internal */
13644
+ async function runCommand(name, params, context) {
13645
+ const commands = registry().commands;
13646
+ const cmd = commands.get(name);
13647
+ if (!cmd) throw new Error(`Unknown command: ${name}. Available: ${[...commands.keys()].join(", ")}`);
13648
+ return await cmd.handler(params, context);
13649
+ }
13650
+ /**
13651
+ * Register a storage event handler.
13652
+ *
13653
+ * @param bucket - Bucket name (or `"*"` for all buckets)
13654
+ * @param handler - Handler function for storage events
13655
+ * @param options - Handler options
13656
+ * @returns Unsubscribe function
13657
+ */
13658
+ function onStorageEvent(bucket, handler, options) {
13659
+ const state = registry();
13660
+ const id = `storage-${++state.counters.handler}`;
13661
+ state.eventHandlers.set(id, {
13662
+ registration: {
13663
+ id,
13664
+ type: "storage",
13665
+ source: bucket,
13666
+ prefix: options?.prefix
13667
+ },
13668
+ handler
13669
+ });
13670
+ return () => {
13671
+ state.eventHandlers.delete(id);
13672
+ };
13673
+ }
13674
+ /**
13675
+ * Register a cron/scheduled event handler.
13676
+ *
13677
+ * @param scheduleName - Schedule name (or `"*"` for all schedules)
13678
+ * @param handler - Handler function for scheduled events
13679
+ * @returns Unsubscribe function
13680
+ */
13681
+ function onCronEvent(scheduleName, handler) {
13682
+ const state = registry();
13683
+ const id = `cron-${++state.counters.handler}`;
13684
+ state.eventHandlers.set(id, {
13685
+ registration: {
13686
+ id,
13687
+ type: "cron",
13688
+ source: scheduleName
13689
+ },
13690
+ handler
13691
+ });
13692
+ return () => {
13693
+ state.eventHandlers.delete(id);
13694
+ };
13695
+ }
13696
+ /**
13697
+ * Register a queue message handler.
13698
+ *
13699
+ * @param queueName - Queue name (or `"*"` for all queues)
13700
+ * @param handler - Handler function for queue messages
13701
+ * @returns Unsubscribe function
13702
+ */
13703
+ function onQueueMessage(queueName, handler) {
13704
+ const state = registry();
13705
+ const id = `queue-${++state.counters.handler}`;
13706
+ state.eventHandlers.set(id, {
13707
+ registration: {
13708
+ id,
13709
+ type: "queue",
13710
+ source: queueName
13711
+ },
13712
+ handler
13713
+ });
13714
+ return () => {
13715
+ state.eventHandlers.delete(id);
13716
+ };
13717
+ }
13718
+ /** Register an opt-in batch handler. Batches may contain fewer than the configured maximum. */
13719
+ function onQueueBatch(queueName, handler) {
13720
+ const state = registry();
13721
+ const id = `queue-batch-${++state.counters.handler}`;
13722
+ state.eventHandlers.set(id, {
13723
+ registration: {
13724
+ id,
13725
+ type: "queueBatch",
13726
+ source: queueName
13727
+ },
13728
+ handler
13729
+ });
13730
+ return () => {
13731
+ state.eventHandlers.delete(id);
13732
+ };
13733
+ }
13734
+ /** Get all registered event handlers. @internal */
13735
+ function getEventHandlers() {
13736
+ return registry().eventHandlers;
13737
+ }
13738
+ /**
13739
+ * Register a background task to continue after the response.
13740
+ *
13741
+ * The runtime waits for all registered tasks to complete before shutting down.
13742
+ * This is the protocol-only registrar: it tracks the promise and (inside a
13743
+ * running Worker) notifies the runtime via the installed hook. The gRPC drain
13744
+ * coordination lives in {@link runWorker}.
13745
+ *
13746
+ * @param promise - The promise to track
13747
+ */
13748
+ function waitUntil(promise) {
13749
+ const state = registry();
13750
+ const id = `task-${++state.counters.task}`;
13751
+ const tracker = {
13752
+ id,
13753
+ promise,
13754
+ registeredAt: /* @__PURE__ */ new Date(),
13755
+ completed: false
13756
+ };
13757
+ state.waitUntilTasks.set(id, tracker);
13758
+ promise.then(() => {
13759
+ tracker.completed = true;
13760
+ }).catch((error) => {
13761
+ tracker.completed = true;
13762
+ tracker.error = error instanceof Error ? error : new Error(String(error));
13763
+ }).finally(() => {
13764
+ state.waitUntilTasks.delete(id);
13765
+ });
13766
+ try {
13767
+ state.onTaskRegistered?.(tracker);
13768
+ } catch (error) {
13769
+ logSystemError("[alien:wait-until] onTaskRegistered hook failed:", error);
13770
+ }
13771
+ }
13772
+ /** Install the runtime's task-registered hook. @internal */
13773
+ function setOnTaskRegistered(hook) {
13774
+ registry().onTaskRegistered = hook;
13775
+ }
13776
+ export { defineError as _, onQueueBatch as a, runCommand as c, logSystemError as d, logSystemWarn as f, StorageEventSchema as g, InvalidBindingConfigError as h, onCronEvent as i, setOnTaskRegistered as l, BindingNotFoundError as m, getCommands as n, onQueueMessage as o, AlienError as p, getEventHandlers as r, onStorageEvent as s, command as t, waitUntil as u, object as v, string as y };
@@ -0,0 +1,11 @@
1
+ import { type StorageEvent } from "@alienplatform/core";
2
+ /**
3
+ * Decode a storage notification from either a Worker queue delivery or `queue.receive()`.
4
+ * Validates the canonical event schema, including the timestamp and optional object size.
5
+ * This does not acknowledge the message; acknowledge only after processing succeeds.
6
+ */
7
+ export declare function storageEventFromMessage(message: {
8
+ payload: unknown;
9
+ id?: string;
10
+ }): Promise<StorageEvent>;
11
+ //# sourceMappingURL=storage-events.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage-events.d.ts","sourceRoot":"","sources":["../src/storage-events.ts"],"names":[],"mappings":"AAAA,OAAO,EAA2B,KAAK,YAAY,EAAsB,MAAM,qBAAqB,CAAA;AAgBpG;;;;GAIG;AACH,wBAAsB,uBAAuB,CAAC,OAAO,EAAE;IACrD,OAAO,EAAE,OAAO,CAAA;IAChB,EAAE,CAAC,EAAE,MAAM,CAAA;CACZ,GAAG,OAAO,CAAC,YAAY,CAAC,CAUxB"}
@@ -1,4 +1,4 @@
1
- import { _ as logSystemError, a as object, c as getCommands, h as setOnTaskRegistered, i as defineError, l as getEventHandlers, m as runCommand, o as string, t as AlienError, v as logSystemWarn } from "../dist.js";
1
+ import { _ as defineError, c as runCommand, d as logSystemError, f as logSystemWarn, l as setOnTaskRegistered, n as getCommands, p as AlienError, r as getEventHandlers, v as object, y as string } from "../registry.js";
2
2
  import { createRequire } from "node:module";
3
3
  import { formatWithOptions } from "node:util";
4
4
  // \0rolldown/runtime.js
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alienplatform/sdk",
3
- "version": "3.3.46",
3
+ "version": "3.3.47",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist"
@@ -57,9 +57,9 @@
57
57
  "nice-grpc": "^2.1.11",
58
58
  "nice-grpc-common": "^2.0.2",
59
59
  "zod": "^4.5.2",
60
- "@alienplatform/ai-gateway": "^3.3.46",
61
- "@alienplatform/bindings": "^3.3.46",
62
- "@alienplatform/core": "^3.3.46"
60
+ "@alienplatform/ai-gateway": "^3.3.47",
61
+ "@alienplatform/bindings": "^3.3.47",
62
+ "@alienplatform/core": "^3.3.47"
63
63
  },
64
64
  "scripts": {
65
65
  "build": "tsdown && tsc --emitDeclarationOnly",