@funcd-dev/shim 0.11.0 → 0.13.0

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/blob.js CHANGED
@@ -3,34 +3,8 @@
3
3
  // to the binding-gated, PDP-authorized Facade with the sandbox's function identity (bind-as-grant on
4
4
  // spec.blob). Reached only through the built-in shim — no @aws-sdk, no keypair. The blob twin of context.kv;
5
5
  // v1 is bytes-in-memory (streaming is a v2 follow-up).
6
- import http from 'node:http';
7
- import { MEMBER_HEADER } from "./invoke.js";
8
- function send(method, path, body, member) {
9
- return new Promise((resolve, reject) => {
10
- const socketPath = process.env.FUNCD_INVOKE_SOCKET;
11
- if (!socketPath) {
12
- reject(new Error('context.blob: worker-node local API socket unavailable (FUNCD_INVOKE_SOCKET unset)'));
13
- return;
14
- }
15
- const headers = {};
16
- if (body)
17
- headers['content-length'] = body.byteLength;
18
- if (member)
19
- headers[MEMBER_HEADER] = member;
20
- const req = http.request({ socketPath, path, method, headers }, (res) => {
21
- const chunks = [];
22
- // A connection that drops mid-body errors the response, not the request, and never ends it.
23
- res.on('error', (err) => reject(new Error(`context.blob ${method} ${path} failed: connection closed before the reply ended`, { cause: err })));
24
- res.on('data', (c) => chunks.push(c));
25
- res.on('end', () => resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks) }));
26
- });
27
- req.on('error', (err) => reject(new Error(`context.blob ${method} ${path} failed: ${err.message}`, { cause: err })));
28
- if (body)
29
- req.end(body);
30
- else
31
- req.end();
32
- });
33
- }
6
+ import { send as sendOn } from "./socket.js";
7
+ const send = (method, path, body, member) => sendOn('context.blob', method, path, body, member);
34
8
  const enc = encodeURIComponent;
35
9
  // key may be hierarchical ("a/b"); keep the "/" separators (the server's {key...} captures them), encode segments.
36
10
  const keyPath = (binding, key) => `/blob/${enc(binding)}/${key.split('/').map(enc).join('/')}`;
package/dist/kv.js CHANGED
@@ -1,34 +1,8 @@
1
1
  // context.kv — function-facing KV over the worker-node local API (HTTP-over-UDS, ADR-0069). Dials the
2
2
  // same per-sandbox socket as context.invoke (FUNCD_INVOKE_SOCKET); the platform routes /kv/… to the
3
3
  // PDP-authorized Facade with the sandbox's namespace identity. Reached only through the built-in shim.
4
- import http from 'node:http';
5
- import { MEMBER_HEADER } from "./invoke.js";
6
- function send(method, path, body, member) {
7
- return new Promise((resolve, reject) => {
8
- const socketPath = process.env.FUNCD_INVOKE_SOCKET;
9
- if (!socketPath) {
10
- reject(new Error('context.kv: worker-node local API socket unavailable (FUNCD_INVOKE_SOCKET unset)'));
11
- return;
12
- }
13
- const headers = {};
14
- if (body)
15
- headers['content-length'] = body.byteLength;
16
- if (member)
17
- headers[MEMBER_HEADER] = member;
18
- const req = http.request({ socketPath, path, method, headers }, (res) => {
19
- const chunks = [];
20
- // A connection that drops mid-body errors the response, not the request, and never ends it.
21
- res.on('error', (err) => reject(new Error(`context.kv ${method} ${path} failed: connection closed before the reply ended`, { cause: err })));
22
- res.on('data', (c) => chunks.push(c));
23
- res.on('end', () => resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks) }));
24
- });
25
- req.on('error', (err) => reject(new Error(`context.kv ${method} ${path} failed: ${err.message}`, { cause: err })));
26
- if (body)
27
- req.end(body);
28
- else
29
- req.end();
30
- });
31
- }
4
+ import { send as sendOn } from "./socket.js";
5
+ const send = (method, path, body, member) => sendOn('context.kv', method, path, body, member);
32
6
  const enc = encodeURIComponent;
33
7
  // key may be hierarchical ("a/b"); keep the "/" separators (the server's {key...} captures them), encode segments.
34
8
  const keyPath = (binding, key) => `/kv/${enc(binding)}/${key.split('/').map(enc).join('/')}`;
@@ -0,0 +1,6 @@
1
+ export interface Resp {
2
+ status: number;
3
+ body: Buffer;
4
+ }
5
+ /** send makes one request; `client` names the context client in its errors ("context.kv"). */
6
+ export declare function send(client: string, method: string, path: string, body: Buffer | undefined, member: string | undefined, contentType?: string): Promise<Resp>;
package/dist/socket.js ADDED
@@ -0,0 +1,33 @@
1
+ // The worker-node local API client shared by context.kv, context.blob and context.sql: one HTTP request over the
2
+ // per-sandbox socket (FUNCD_INVOKE_SOCKET), as the calling pool member when one is given.
3
+ import http from 'node:http';
4
+ import { MEMBER_HEADER } from "./invoke.js";
5
+ /** send makes one request; `client` names the context client in its errors ("context.kv"). */
6
+ export function send(client, method, path, body, member, contentType) {
7
+ return new Promise((resolve, reject) => {
8
+ const socketPath = process.env.FUNCD_INVOKE_SOCKET;
9
+ if (!socketPath) {
10
+ reject(new Error(`${client}: worker-node local API socket unavailable (FUNCD_INVOKE_SOCKET unset)`));
11
+ return;
12
+ }
13
+ const headers = {};
14
+ if (body)
15
+ headers['content-length'] = body.byteLength;
16
+ if (contentType)
17
+ headers['content-type'] = contentType;
18
+ if (member)
19
+ headers[MEMBER_HEADER] = member;
20
+ const req = http.request({ socketPath, path, method, headers }, (res) => {
21
+ const chunks = [];
22
+ // A connection that drops mid-body errors the response, not the request, and never ends it.
23
+ res.on('error', (err) => reject(new Error(`${client} ${method} ${path} failed: connection closed before the reply ended`, { cause: err })));
24
+ res.on('data', (c) => chunks.push(c));
25
+ res.on('end', () => resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks) }));
26
+ });
27
+ req.on('error', (err) => reject(new Error(`${client} ${method} ${path} failed: ${err.message}`, { cause: err })));
28
+ if (body)
29
+ req.end(body);
30
+ else
31
+ req.end();
32
+ });
33
+ }
package/dist/sql.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ /** A SQL parameter: rqlite takes JSON scalars. Integers past 2^53 lose precision. */
2
+ export type SQLParam = string | number | boolean | null;
3
+ /** Positional parameters for `?`, or one map for `:name`. */
4
+ export type SQLParams = SQLParam[] | Record<string, SQLParam>;
5
+ /** One statement of a batch: its SQL text, with its parameters. */
6
+ export type SQLStatement = string | [sql: string, params?: SQLParams];
7
+ /** A row as an object; with a duplicate column name the last one wins (use queryValues to keep every column). */
8
+ export type SQLRow = Record<string, unknown>;
9
+ /** Rows as columns and arrays of values, as rqlite returns them: every column of a join is kept. */
10
+ export interface SQLValues {
11
+ columns: string[];
12
+ values: unknown[][];
13
+ }
14
+ /** The outcome of one executed statement; a RETURNING statement also carries its rows. */
15
+ export interface SQLExecResult {
16
+ rowsAffected: number;
17
+ lastInsertId: number;
18
+ columns?: string[];
19
+ values?: unknown[][];
20
+ }
21
+ /** A function's view of the SQL databases it binds (spec.sql), by alias. */
22
+ export interface SQLClient {
23
+ query(alias: string, sql: string, params?: SQLParams): Promise<SQLRow[]>;
24
+ queryValues(alias: string, sql: string, params?: SQLParams): Promise<SQLValues>;
25
+ execute(alias: string, sql: string, params?: SQLParams): Promise<SQLExecResult>;
26
+ execute(alias: string, statements: SQLStatement[]): Promise<SQLExecResult[]>;
27
+ }
28
+ /** Build the context.sql client. In a pool, `member` names the calling function on every request. */
29
+ export declare function makeSQL(member?: string): SQLClient;
package/dist/sql.js ADDED
@@ -0,0 +1,52 @@
1
+ // context.sql — function-facing SQL over the worker-node local API (funcd ADR-0233). Dials the per-sandbox socket
2
+ // (FUNCD_INVOKE_SOCKET); the platform routes /sql/… to the PDP-authorized facade with the sandbox's identity, and
3
+ // the database's engine and credential never reach the sandbox. query runs read-only; execute runs its statements
4
+ // in one transaction, all or nothing.
5
+ import { send } from "./socket.js";
6
+ /** wire is a statement in the local API's form: ["SQL", p1, p2, …] or ["SQL", {name: value}]. */
7
+ function wire(sql, params) {
8
+ if (params === undefined)
9
+ return [sql];
10
+ return Array.isArray(params) ? [sql, ...params] : [sql, params];
11
+ }
12
+ function toWire(s) {
13
+ return typeof s === 'string' ? [s] : wire(s[0], s[1]);
14
+ }
15
+ /** Build the context.sql client. In a pool, `member` names the calling function on every request. */
16
+ export function makeSQL(member) {
17
+ async function call(verb, alias, statements) {
18
+ const path = `/sql/${encodeURIComponent(alias)}/${verb}`;
19
+ const body = Buffer.from(JSON.stringify({ statements }), 'utf8');
20
+ const r = await send('context.sql', 'POST', path, body, member, 'application/json');
21
+ const text = r.body.toString('utf8');
22
+ if (r.status < 200 || r.status >= 300)
23
+ throw new Error(`context.sql.${verb} failed: ${r.status} ${text}`);
24
+ try {
25
+ return JSON.parse(text).results;
26
+ }
27
+ catch (err) {
28
+ throw new Error(`context.sql.${verb} failed: ${r.status} reply is not JSON: ${err.message}`, {
29
+ cause: err,
30
+ });
31
+ }
32
+ }
33
+ async function queryValues(alias, sql, params) {
34
+ const [res] = await call('query', alias, [wire(sql, params)]);
35
+ return res;
36
+ }
37
+ async function execute(alias, sqlOrStatements, params) {
38
+ if (typeof sqlOrStatements === 'string') {
39
+ const [res] = await call('execute', alias, [wire(sqlOrStatements, params)]);
40
+ return res;
41
+ }
42
+ return call('execute', alias, sqlOrStatements.map(toWire));
43
+ }
44
+ return {
45
+ async query(alias, sql, params) {
46
+ const { columns, values } = await queryValues(alias, sql, params);
47
+ return values.map((row) => Object.fromEntries(columns.map((c, i) => [c, row[i]])));
48
+ },
49
+ queryValues,
50
+ execute,
51
+ };
52
+ }
package/dist/types.d.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import type { KVClient } from './kv.ts';
2
2
  import type { BlobClient } from './blob.ts';
3
+ import type { SQLClient } from './sql.ts';
3
4
  export type { KVClient } from './kv.ts';
4
5
  export type { BlobClient, SignOptions } from './blob.ts';
6
+ export type { SQLClient, SQLExecResult, SQLParam, SQLParams, SQLRow, SQLStatement, SQLValues, } from './sql.ts';
5
7
  /** A CloudEvent — the normalized trigger envelope (ADR-0023). */
6
8
  export interface CloudEvent<T = unknown> {
7
9
  id: string;
@@ -33,6 +35,9 @@ export interface FunctionContext {
33
35
  /** Binding-scoped blob storage (ADR-0127): get/put/del/list a bound prefix's objects, or mint a
34
36
  * presigned URL — the blob twin of kv. */
35
37
  blob: BlobClient;
38
+ /** The SQL databases a function binds (funcd ADR-0233): query reads, queryValues keeps every column of a join,
39
+ * execute writes in one transaction. A write needs the database's owner or a writer role. */
40
+ sql: SQLClient;
36
41
  /** Milliseconds left before the call's deadline (X-Funcd-Timeout-Ms), floored at 0; null without one (ADR-0226). */
37
42
  remainingMs(): number | null;
38
43
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@funcd-dev/shim",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "type": "module",
5
5
  "description": "Types and the contract build for writing funcd functions in TypeScript",
6
6
  "license": "Apache-2.0",