@lifesi/genesis 0.1.0 → 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.
package/dist/client.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { operationTable, services } from './generated/operations.js';
2
2
  import { GenesisError } from './errors.js';
3
+ import { validateHivesInvocation, hivesFunctionResponseHeaders, hivesFunctionMetadata } from './hives-functions.js';
3
4
  export const DEFAULT_BASE_URL = 'https://console.life.one/api';
4
5
  const env = globalThis.process?.env ?? {};
5
6
  export class GenesisClient {
@@ -59,14 +60,36 @@ export class GenesisClient {
59
60
  /** Call any Genesis operation by id, fully typed from the merged spec. */
60
61
  async request(operationId, input, init = {}) {
61
62
  const res = await this.raw(operationId, (input ?? {}), init);
63
+ if (operationTable[operationId].rawResponse)
64
+ return res;
62
65
  if (res.status === 204)
63
66
  return undefined;
64
67
  const ct = res.headers.get('content-type') ?? '';
65
- return (ct.includes('json') ? await res.json() : await res.text());
68
+ let value;
69
+ try {
70
+ value = ct.includes('json') ? await res.json() : await res.text();
71
+ }
72
+ catch (error) {
73
+ if (String(operationId).startsWith('hives_') && /_functions?$/.test(operationId))
74
+ throw new Error('Hives returned invalid function metadata.');
75
+ throw error;
76
+ }
77
+ if (operationId === 'hives_list_functions') {
78
+ if (!value || !Array.isArray(value.data) || !value.pagination)
79
+ throw new Error('Hives returned invalid function list metadata.');
80
+ const pagination = Object.fromEntries(['page', 'per_page', 'total', 'total_pages', 'has_next', 'has_prev'].map((key) => [key, value.pagination[key]]));
81
+ return { data: value.data.map((row) => hivesFunctionMetadata(row, input?.project_id)), pagination };
82
+ }
83
+ if (['hives_get_function', 'hives_create_function', 'hives_update_function'].includes(operationId)) {
84
+ return hivesFunctionMetadata(value, input?.project_id);
85
+ }
86
+ return value;
66
87
  }
67
- /** Like request() but returns the raw Response (for streaming). Throws GenesisError on non-2xx. */
88
+ /** Raw Response. Completed Hives guest responses retain their actual status, including non-2xx. */
68
89
  async raw(operationId, input = {}, init = {}) {
69
90
  const op = operationTable[operationId];
91
+ if (op.rawResponse && op.service === 'hives')
92
+ validateHivesInvocation(input.body);
70
93
  const url = this.url(operationId, input);
71
94
  const headers = {
72
95
  accept: 'application/json',
@@ -83,10 +106,72 @@ export class GenesisClient {
83
106
  }
84
107
  let body;
85
108
  if (op.hasBody && input.body !== undefined) {
86
- headers['content-type'] = 'application/json';
87
- body = JSON.stringify(input.body);
109
+ // Fetch owns multipart boundary generation. Never serialize a File/Blob as JSON.
110
+ for (const key of Object.keys(headers))
111
+ if (key.toLowerCase() === 'content-type')
112
+ delete headers[key];
113
+ if (op.requestContentType === 'multipart/form-data') {
114
+ if (!(input.body instanceof FormData))
115
+ throw new GenesisError({ status: 0, type: 'invalid_request', operationId,
116
+ message: 'This operation requires a FormData body containing a real binary file.' });
117
+ body = input.body;
118
+ }
119
+ else {
120
+ if (input.body instanceof FormData || input.body instanceof Blob || input.body instanceof ArrayBuffer || ArrayBuffer.isView(input.body)) {
121
+ throw new GenesisError({ status: 0, type: 'invalid_request', operationId, message: 'This operation requires a JSON body.' });
122
+ }
123
+ headers['content-type'] = 'application/json';
124
+ body = JSON.stringify(input.body);
125
+ }
126
+ }
127
+ const secretOperation = op.service === 'hives' && /_secrets?$/.test(operationId);
128
+ const functionOperation = op.service === 'hives' && (op.rawResponse || /_function(?:s|_async)?$/.test(operationId));
129
+ let res;
130
+ try {
131
+ res = await this.fetchImpl(url, { method: op.method, headers, body, signal: init.signal,
132
+ ...(op.service === 'hives' ? { cache: 'no-store', redirect: op.rawResponse ? 'manual' : 'error' } : {}) });
133
+ }
134
+ catch (error) {
135
+ if (functionOperation)
136
+ throw new GenesisError({ status: 0, type: 'transport_error', operationId,
137
+ message: 'Hives function transport failed. No redirects are followed; check the service address and retry.' });
138
+ if (!secretOperation)
139
+ throw error;
140
+ throw new GenesisError({ status: 0, type: 'transport_error', operationId,
141
+ message: 'Hives secret transport failed. Redirects are refused; check the service address and retry.' });
142
+ }
143
+ if (op.rawResponse && /^exec_[a-f0-9]{32}$/.test(res.headers.get('x-execution-id') ?? '')) {
144
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers: hivesFunctionResponseHeaders(res.headers) });
145
+ }
146
+ if (op.rawResponse && res.ok)
147
+ throw new GenesisError({ status: res.status, type: 'invalid_response', operationId,
148
+ message: 'Hives did not confirm a completed guest execution. Refresh the resource and retry.' });
149
+ if (functionOperation && !res.ok) {
150
+ const message = res.status === 401 ? 'Genesis credential rejected. Sign in again.'
151
+ : res.status === 403 ? 'Missing the authorized Hives scope for this function action.'
152
+ : res.status === 404 ? 'Function/deployment, project or artifact not found in the authenticated organization and project.'
153
+ : res.status === 409 ? 'Function mutation conflicted. Refresh its metadata before retrying.'
154
+ : res.status === 400 || res.status === 422 ? 'Invalid function request. Check artifact, resource bounds and guest request syntax.'
155
+ : res.status === 413 ? 'Function request exceeds a body or serialized guest envelope limit.'
156
+ : res.status >= 300 && res.status < 400 ? 'Unexpected function service redirect. No redirect was followed.'
157
+ : `Hives function operation failed (${res.status}). Refresh and retry.`;
158
+ throw new GenesisError({ status: res.status, type: `http_${res.status}`, operationId, message,
159
+ requestId: res.headers.get('x-request-id') ?? undefined });
160
+ }
161
+ if (!res.ok && secretOperation) {
162
+ const message = res.status === 401 ? 'Genesis credential rejected. Sign in again.'
163
+ : res.status === 403 ? 'Missing the authorized Hives scope for this action (hives:read or hives:write).'
164
+ : res.status === 404 ? 'Secret or project not found in your authenticated organization.'
165
+ : res.status === 409 ? 'A secret with this name already exists. Update it instead.'
166
+ : res.status === 400 || res.status === 422 ? 'Invalid secret request. Check names and UTF-8 value size.'
167
+ : res.status === 413 ? 'Secret request too large. Use a smaller batch.'
168
+ : res.status === 429 ? 'Too many requests. Wait briefly before retrying.'
169
+ : res.status === 503 ? 'Hives customer encryption is unavailable or stored secrets require protected migration.'
170
+ : `Hives secret operation failed (${res.status}). Refresh metadata and retry.`;
171
+ // Validation/provider bodies may reflect submitted plaintext. Never retain or log them.
172
+ throw new GenesisError({ status: res.status, type: `http_${res.status}`, message, operationId,
173
+ requestId: res.headers.get('x-request-id') ?? undefined });
88
174
  }
89
- const res = await this.fetchImpl(url, { method: op.method, headers, body, signal: init.signal });
90
175
  if (!res.ok)
91
176
  throw await GenesisError.fromResponse(res, operationId);
92
177
  return res;
package/dist/dials.d.ts CHANGED
@@ -8,16 +8,91 @@ export type DialsOutboundCall = components['schemas']['Dials.OutboundCall'];
8
8
  export type DialsEmergencyAddress = components['schemas']['Dials.RegisterEmergencyAddress'];
9
9
  /** Scope is selection only; the Dials backend verifies its org against signed identity. */
10
10
  export declare function dialsModule(client: GenesisClient): {
11
+ overview: {
12
+ summary: (scope: DialsScope) => Promise<{
13
+ ok: boolean;
14
+ scope: components["schemas"]["Dials.Scope"];
15
+ calls: {
16
+ total: number;
17
+ queued: number;
18
+ active: number;
19
+ completed: number;
20
+ failed: number;
21
+ };
22
+ dispatch: {
23
+ total: number;
24
+ pending: number;
25
+ claimed: number;
26
+ dispatched: number;
27
+ failed: number;
28
+ };
29
+ people: {
30
+ deployed: number;
31
+ };
32
+ agents: {
33
+ deployed: number;
34
+ };
35
+ routes: {
36
+ deployed: number;
37
+ };
38
+ numbers: {
39
+ deployed: number;
40
+ };
41
+ voice: {
42
+ deployed: number;
43
+ };
44
+ messages: {
45
+ total: number;
46
+ queued: number;
47
+ delivered: number;
48
+ failed: number;
49
+ };
50
+ usage: {
51
+ total: number;
52
+ quantity: number;
53
+ lastMetric: string | null;
54
+ lastResourceId: string | null;
55
+ };
56
+ }>;
57
+ operatingSurface: (scope: DialsScope) => Promise<{
58
+ ok: boolean;
59
+ scope: components["schemas"]["Dials.Scope"];
60
+ summary: components["schemas"]["Dials.ConsoleSummary"];
61
+ surfaces: components["schemas"]["Dials.OperatingSurfaceCard"][];
62
+ } & {
63
+ [key: string]: unknown;
64
+ }>;
65
+ };
11
66
  numbers: {
67
+ reconciliations: (scope: DialsScope) => Promise<{
68
+ ok: boolean;
69
+ reconciliations: components["schemas"]["Dials.InventoryReconciliation"][];
70
+ }>;
71
+ drift: (scope: DialsScope) => Promise<{
72
+ ok: boolean;
73
+ drift: components["schemas"]["Dials.InventoryDrift"][];
74
+ }>;
75
+ updateCallerName: (body: OperationInput<"dials_updateNumberCallerName">["body"]) => Promise<{
76
+ ok: boolean;
77
+ number: components["schemas"]["Dials.Number"];
78
+ auditId: string;
79
+ next: string;
80
+ }>;
81
+ reconcile: (body: OperationInput<"dials_reconcileNumberInventory">["body"]) => Promise<{
82
+ ok: boolean;
83
+ reconciliations: components["schemas"]["Dials.InventoryReconciliation"][];
84
+ drift: components["schemas"]["Dials.InventoryDrift"][];
85
+ orphanCount: number;
86
+ auditId: string;
87
+ next: string;
88
+ }>;
12
89
  list: (scope: DialsScope) => Promise<{
13
90
  ok: boolean;
14
91
  numbers: components["schemas"]["Dials.Number"][];
15
92
  }>;
16
- search: (scope: DialsScope, query?: {
17
- areaCode?: string;
18
- limit?: number;
19
- }) => Promise<{
20
- [key: string]: unknown;
93
+ search: (scope: DialsScope, query?: Omit<OperationInput<"dials_searchNumbers">, keyof DialsScope>) => Promise<{
94
+ ok: boolean;
95
+ numbers: components["schemas"]["Dials.AvailableNumber"][];
21
96
  }>;
22
97
  provision: (body: OperationInput<"dials_provisionNumber">["body"]) => Promise<{
23
98
  [key: string]: unknown;
@@ -49,3 +124,6 @@ export declare function dialsModule(client: GenesisClient): {
49
124
  }>;
50
125
  };
51
126
  };
127
+ export type DialsEmergencyAddressFeedback = components['schemas']['Dials.EmergencyAddressFeedback'];
128
+ /** Read bounded, typed advisory feedback from the existing Genesis error. Never auto-apply it. */
129
+ export declare function dialsEmergencyAddressFeedback(error: unknown): DialsEmergencyAddressFeedback | undefined;
package/dist/dials.js CHANGED
@@ -1,9 +1,18 @@
1
+ import { GenesisError } from './errors.js';
1
2
  /** Scope is selection only; the Dials backend verifies its org against signed identity. */
2
3
  export function dialsModule(client) {
3
4
  return {
5
+ overview: {
6
+ summary: (scope) => client.request('dials_getConsoleSummary', scope),
7
+ operatingSurface: (scope) => client.request('dials_getOperatingSurface', scope),
8
+ },
4
9
  numbers: {
10
+ reconciliations: (scope) => client.request('dials_listNumberReconciliations', scope),
11
+ drift: (scope) => client.request('dials_listNumberDrift', scope),
12
+ updateCallerName: (body) => client.request('dials_updateNumberCallerName', { body }),
13
+ reconcile: (body) => client.request('dials_reconcileNumberInventory', { body }),
5
14
  list: (scope) => client.request('dials_listNumbers', scope),
6
- search: (scope, query = {}) => client.request('dials_searchNumbers', { ...scope, ...query }),
15
+ search: (scope, query = {}) => client.request('dials_searchNumbers', { ...query, ...scope }),
7
16
  provision: (body) => client.request('dials_provisionNumber', { body }),
8
17
  assign: (body) => client.request('dials_assignNumber', { body }),
9
18
  release: (body) => client.request('dials_releaseNumber', { body }),
@@ -16,3 +25,35 @@ export function dialsModule(client) {
16
25
  },
17
26
  };
18
27
  }
28
+ const fields = { streetNumber: 'Review the street number.', streetName: 'Review the street name.', addressLine2: 'Review the suite or unit type and number.', city: 'Review the city.', region: 'Review the state.', postalCode: 'Review the postal code.', country: 'Review the country.', address: 'The carrier could not validate this address. Review the address and any suggestions.' };
29
+ const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
30
+ const addressText = (value, max) => typeof value === 'string' && value.length > 0 && value.length <= max && /^[\p{L}\p{N} .,'#/-]+$/u.test(value) && !/(bearer|basic |sk_|api_key|authorization|secret|token=)/i.test(value);
31
+ /** Read bounded, typed advisory feedback from the existing Genesis error. Never auto-apply it. */
32
+ export function dialsEmergencyAddressFeedback(error) {
33
+ if (!(error instanceof GenesisError) || error.status !== 422 || error.operationId !== 'dials_registerEmergencyAddress')
34
+ return;
35
+ const body = error.body;
36
+ if (!object(body) || body.error !== 'carrier_rejected' || body.automaticCorrection !== false || !Array.isArray(body.fieldErrors) || !body.fieldErrors.length || body.fieldErrors.length > 8 || !Array.isArray(body.candidates) || body.candidates.length > 5)
37
+ return;
38
+ const fieldErrors = [];
39
+ for (const value of body.fieldErrors) {
40
+ if (!object(value) || typeof value.field !== 'string' || !Object.hasOwn(fields, value.field) || !['required', 'invalid', 'not_found', 'ambiguous', 'not_validated'].includes(String(value.code)))
41
+ return;
42
+ const field = value.field;
43
+ fieldErrors.push({ field, code: value.code, message: fields[field] });
44
+ }
45
+ const candidates = [];
46
+ for (const value of body.candidates) {
47
+ if (!object(value) || !addressText(value.streetNumber, 32) || !addressText(value.streetName, 128) || !addressText(value.city, 80) || typeof value.region !== 'string' || !/^[A-Za-z]{2}$/.test(value.region) || typeof value.postalCode !== 'string' || !/^\d{5}(?:-\d{4})?$/.test(value.postalCode))
48
+ return;
49
+ const extra = {};
50
+ if (value.addressType !== undefined || value.addressNumber !== undefined) {
51
+ if (!['Apartment', 'Basement', 'Building', 'Department', 'Floor', 'Office', 'Penthouse', 'Suite', 'Trailer', 'Unit'].includes(String(value.addressType)) || !addressText(value.addressNumber, 32))
52
+ return;
53
+ extra.addressType = value.addressType;
54
+ extra.addressNumber = value.addressNumber;
55
+ }
56
+ candidates.push({ streetNumber: value.streetNumber, streetName: value.streetName, city: value.city, region: value.region, postalCode: value.postalCode, ...extra });
57
+ }
58
+ return { automaticCorrection: false, fieldErrors, candidates };
59
+ }