@hugex/artifact 0.0.0-stage → 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.
@@ -0,0 +1,48 @@
1
+ export declare function frameAncestorsDirective(raw: string | undefined): string;
2
+ export declare function artifactCsp(frameAncestors?: string): string;
3
+ /** Default CSP when `ARTIFACT_FRAME_ANCESTORS` is empty: `frame-ancestors 'none'`. */
4
+ export declare const ARTIFACT_CSP: string;
5
+ /**
6
+ * Font override for HugeX theme.
7
+ */
8
+ export declare const THEME_FONTS_CSS = " --font-sans: \"PolySans\", ui-sans-serif, system-ui, sans-serif;\n --font-inter: \"Inter\", ui-sans-serif, system-ui, sans-serif;";
9
+ /**
10
+ * Color and surface tokens copied from hx-base/packages/ui/base.css.
11
+ * These are additive and safe to keep active across all artifacts.
12
+ */
13
+ export declare const THEME_TOKENS_CSS = " --color-primary-50: var(--theme-primary-50);\n --color-primary-100: var(--theme-primary-100);\n --color-primary-200: var(--theme-primary-200);\n --color-primary-300: var(--theme-primary-300);\n --color-primary-400: var(--theme-primary-400);\n --color-primary-500: var(--theme-primary-500);\n --color-primary-600: var(--theme-primary-600);\n --color-primary-700: var(--theme-primary-700);\n --color-primary-800: var(--theme-primary-800);\n --color-primary-900: var(--theme-primary-900);\n\n --color-secondary-50: var(--theme-secondary-50);\n --color-secondary-100: var(--theme-secondary-100);\n --color-secondary-200: var(--theme-secondary-200);\n --color-secondary-300: var(--theme-secondary-300);\n --color-secondary-400: var(--theme-secondary-400);\n --color-secondary-500: var(--theme-secondary-500);\n --color-secondary-600: var(--theme-secondary-600);\n --color-secondary-700: var(--theme-secondary-700);\n --color-secondary-800: var(--theme-secondary-800);\n --color-secondary-900: var(--theme-secondary-900);\n\n --color-warning-50: var(--theme-warning-50);\n --color-warning-100: var(--theme-warning-100);\n --color-warning-200: var(--theme-warning-200);\n --color-warning-300: var(--theme-warning-300);\n --color-warning-400: var(--theme-warning-400);\n --color-warning-500: var(--theme-warning-500);\n --color-warning-600: var(--theme-warning-600);\n --color-warning-700: var(--theme-warning-700);\n --color-warning-800: var(--theme-warning-800);\n --color-warning-900: var(--theme-warning-900);\n\n --color-danger-50: var(--theme-danger-50);\n --color-danger-100: var(--theme-danger-100);\n --color-danger-200: var(--theme-danger-200);\n --color-danger-300: var(--theme-danger-300);\n --color-danger-400: var(--theme-danger-400);\n --color-danger-500: var(--theme-danger-500);\n --color-danger-600: var(--theme-danger-600);\n --color-danger-700: var(--theme-danger-700);\n --color-danger-800: var(--theme-danger-800);\n --color-danger-900: var(--theme-danger-900);\n\n --color-bg-base: var(--theme-bg-base);\n --color-bg-surface: var(--theme-bg-surface);\n --color-border-subtle: var(--theme-border-subtle);\n --color-text-base: var(--theme-text-base);\n --color-text-muted: var(--theme-text-muted);";
14
+ export declare function buildThemeCss(theme?: "hugex" | "none"): string;
15
+ /**
16
+ * Default THEME_CSS (backward compatible full theme including fonts).
17
+ */
18
+ export declare const THEME_CSS: string;
19
+ /**
20
+ * Light `:root` variables copied from hx-base/packages/ui/base.css.
21
+ * `@theme` references these; without them the color utilities do not resolve.
22
+ */
23
+ export declare const ROOT_CSS = ":root,\n[data-theme=\"light\"] {\n --theme-primary-50: #FAF5FF;\n --theme-primary-100: #F0E0FF;\n --theme-primary-200: #E2C2FF;\n --theme-primary-300: #D4A3FF;\n --theme-primary-400: #C27DFF;\n --theme-primary-500: #AB63FF;\n --theme-primary-600: #944FE0;\n --theme-primary-700: #7A3BC2;\n --theme-primary-800: #5F2D99;\n --theme-primary-900: #452070;\n\n --theme-secondary-50: #EFF6FF;\n --theme-secondary-100: #DBEAFE;\n --theme-secondary-200: #BFDBFE;\n --theme-secondary-300: #93C5FD;\n --theme-secondary-400: #60A5FA;\n --theme-secondary-500: #3B82F6;\n --theme-secondary-600: #2563EB;\n --theme-secondary-700: #1D4ED8;\n --theme-secondary-800: #1E40AF;\n --theme-secondary-900: #1E3A8A;\n\n --theme-warning-50: #FEFCE8;\n --theme-warning-100: #FEF9C3;\n --theme-warning-200: #FEF08A;\n --theme-warning-300: #FDE047;\n --theme-warning-400: #FACC15;\n --theme-warning-500: #EAB308;\n --theme-warning-600: #CA8A04;\n --theme-warning-700: #A16207;\n --theme-warning-800: #854D0E;\n --theme-warning-900: #713F12;\n\n --theme-danger-50: #FEF2F2;\n --theme-danger-100: #FEE2E2;\n --theme-danger-200: #FECACA;\n --theme-danger-300: #FCA5A5;\n --theme-danger-400: #F87171;\n --theme-danger-500: #EF4444;\n --theme-danger-600: #DC2626;\n --theme-danger-700: #B91C1C;\n --theme-danger-800: #991B1B;\n --theme-danger-900: #7F1D1D;\n\n --theme-bg-base: #EFEBF5;\n --theme-bg-surface: #F9F8FC;\n --theme-border-subtle: #dad3ed;\n --theme-text-base: #2A2438;\n --theme-text-muted: #7E7492;\n}";
24
+ export interface InjectOptions {
25
+ /** Public base path of the artifact, including the trailing slash. */
26
+ baseHref: string;
27
+ imports: Record<string, string>;
28
+ integrity: Record<string, string>;
29
+ tailwindUrl: string;
30
+ tailwindIntegrity: string;
31
+ theme?: "hugex" | "none";
32
+ stylesheets?: {
33
+ url: string;
34
+ integrity: string;
35
+ }[];
36
+ scripts?: {
37
+ url: string;
38
+ integrity: string;
39
+ defer?: boolean;
40
+ }[];
41
+ }
42
+ /** Insert `<base>`, the process shim, the import map, stylesheets, scripts, Tailwind, theme tokens, and the reload client. */
43
+ export declare function injectHtml(html: string, options: InjectOptions): string;
44
+ /** Resolve `libs` and `theme` from artifact.json and inject. Unknown libs are ignored here; write() reports them. */
45
+ export declare function injectArtifactHtml(html: string, baseHref: string, libs: readonly string[], theme?: "hugex" | "none"): string;
46
+ export declare function contentType(path: string): string;
47
+ /** Referrer-Policy, nosniff, no-transform, and the artifact CSP on every response. No Set-Cookie. */
48
+ export declare function applySecurityHeaders(response: Response, frameAncestors?: string): Response;
@@ -0,0 +1,10 @@
1
+ import type { ArtifactEnv, WriteResult } from "./types";
2
+ export declare const INTERNAL_ARTIFACTS_PATH = "/api/internal/artifacts";
3
+ export declare function isInternalArtifactsPath(pathname: string): boolean;
4
+ /**
5
+ * Constant-time comparison when a key is configured.
6
+ * A missing or empty `HX_API_KEY` is always unauthorized.
7
+ */
8
+ export declare function authorizeInternal(request: Request, env: ArtifactEnv): boolean;
9
+ export declare function handleArtifactInternal(request: Request, env: ArtifactEnv): Promise<Response>;
10
+ export declare function writeHttpStatus(result: WriteResult): number;
@@ -0,0 +1,22 @@
1
+ /** MVP caps from PLAN-ARTIFACTS.md section 10. Byte counts are decimal MB as in the spike. */
2
+ export declare const LIMITS: {
3
+ readonly fileBytes: 1000000;
4
+ readonly versionBytes: 5000000;
5
+ readonly supervisorBytes: 200000000;
6
+ readonly logRows: 1000;
7
+ /** 2 KB, truncated on insert. */
8
+ readonly logMessageBytes: 2048;
9
+ readonly browserLogsPerSecond: 20;
10
+ readonly pathMaxChars: 200;
11
+ /** Shared deadline for facet load, health, and restore. An expired activation cannot publish. */
12
+ readonly healthTimeoutMs: 5000;
13
+ /** Non-active version rows kept by created_at (plus active and log-referenced versions). */
14
+ readonly keepVersions: 50;
15
+ };
16
+ /**
17
+ * compatibilityDate pinned on every Dynamic Worker.
18
+ * The outer tenant worker can stay older; the loader sets this on the facet isolate.
19
+ * Fase 0 verified loader + facets + facet SQLite on 2025-04-04. 2025-05-15 is the
20
+ * date the Fase 1 integration worker uses.
21
+ */
22
+ export declare const ARTIFACT_COMPATIBILITY_DATE = "2025-05-15";
@@ -0,0 +1,18 @@
1
+ import type { ArtifactEnv } from '../types';
2
+ import type { ArtifactAccess } from './authz';
3
+ export declare const ACCESS_TIMEOUT_MS = 5000;
4
+ export declare const ACCESS_CACHE_MS = 60000;
5
+ export type ResolveAccessResult = {
6
+ ok: true;
7
+ mode: 'phase1';
8
+ } | {
9
+ ok: true;
10
+ mode: 'rbac';
11
+ access: ArtifactAccess;
12
+ } | {
13
+ ok: false;
14
+ status: 401 | 403;
15
+ };
16
+ export declare function rbacConfigured(env: Pick<ArtifactEnv, 'HX_ORA_URL' | 'HX_API_KEY'>): boolean;
17
+ export declare function clearAccessCache(): void;
18
+ export declare function resolveAccess(env: Pick<ArtifactEnv, 'HX_ORA_URL' | 'HX_API_KEY'>, token: string, fetchImpl?: typeof fetch, timeoutMs?: number): Promise<ResolveAccessResult>;
@@ -0,0 +1,32 @@
1
+ /** Entire header value. No lowercase scheme, no extra whitespace, base64url segments only. */
2
+ export declare const BEARER_RE: RegExp;
3
+ export declare const WWW_AUTHENTICATE = "Bearer realm=\"hugex-artifact\"";
4
+ export interface ArtifactIdentity {
5
+ email: string;
6
+ org: string;
7
+ tenant: string;
8
+ }
9
+ export interface AuthEnv {
10
+ TENANT: string;
11
+ /** Keycloak RS256 public key: base64 SPKI body, no PEM armor. */
12
+ KC_RS256_PK: string;
13
+ }
14
+ export declare function parseBearer(authorization: string | null | undefined): string | null;
15
+ export declare function spkiPem(publicKeyBody: string): string;
16
+ /** Import a Keycloak RS256 public key. `publicKey` is the PEM body (or a full PEM). */
17
+ export declare function importRs256PublicKey(publicKey: string): Promise<CryptoKey>;
18
+ export declare function unauthorizedResponse(): Response;
19
+ export declare function canonicalEmail(payload: Record<string, unknown>): string | null;
20
+ /**
21
+ * Verify an already-parsed bearer token.
22
+ * `publicKey` is a CryptoKey or the same SPKI body stored in KC_RS256_PK.
23
+ * Returns null on any failure (bad signature, wrong tenant, missing email).
24
+ */
25
+ export declare function verifyArtifactToken(token: string, publicKey: CryptoKey | string, expectedTenant: string): Promise<ArtifactIdentity | null>;
26
+ export declare function authenticateRequest(request: Request, env: AuthEnv): Promise<{
27
+ ok: true;
28
+ identity: ArtifactIdentity;
29
+ } | {
30
+ ok: false;
31
+ response: Response;
32
+ }>;
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Phase 1: owner only, when hx-ora is not configured.
3
+ * Phase 2: `artifacts` module on every tool, then canUseTool / canManageTool.
4
+ * Those two functions are copied from hx-core-back/hx-ora/src/utils/rbac.ts.
5
+ */
6
+ import type { ArtifactMeta } from '../types';
7
+ import type { ArtifactIdentity } from './auth';
8
+ /** `use` = canUseTool, `manage` = canManageTool. `module` = the artifacts module (list/create). */
9
+ export type ArtifactOp = 'use' | 'manage';
10
+ export type ToolPermission = ArtifactOp | 'module';
11
+ export declare const ARTIFACTS_MODULE = "artifacts";
12
+ /** Same fields hx-ora calls AccessContext. */
13
+ export interface ArtifactAccess {
14
+ userId: string;
15
+ roleIds: string[];
16
+ isAdmin: boolean;
17
+ isSuperAdmin: boolean;
18
+ org: string;
19
+ modules: string[];
20
+ }
21
+ export type ToolAccessRow = {
22
+ owner: string;
23
+ group: string;
24
+ org?: string | null;
25
+ };
26
+ export declare const TOOL_PERMISSION: {
27
+ readonly artifact_list: 'module';
28
+ readonly artifact_create: 'module';
29
+ readonly artifact_read: 'use';
30
+ readonly artifact_logs: 'use';
31
+ readonly artifact_query: 'use';
32
+ readonly artifact_url: 'use';
33
+ readonly artifact_write: 'manage';
34
+ readonly artifact_rollback: 'manage';
35
+ readonly artifact_settings: 'manage';
36
+ readonly artifact_versions: 'use';
37
+ };
38
+ export type ArtifactToolName = keyof typeof TOOL_PERMISSION;
39
+ export declare function isArtifactToolName(name: string): name is ArtifactToolName;
40
+ export declare function hasArtifactsModule(access: ArtifactAccess): boolean;
41
+ /** Design-time: list / view / test / link a tool. */
42
+ export declare function canUseTool(row: ToolAccessRow, ctx: ArtifactAccess): boolean;
43
+ /** Design-time: modify / delete / manage refs & connections. Owner or admin only. */
44
+ export declare function canManageTool(row: ToolAccessRow, ctx: ArtifactAccess): boolean;
45
+ /**
46
+ * Fail-closed. Without an access context (Phase 1) only the owner is allowed.
47
+ * With a context, `use` is canUseTool and `manage` is canManageTool.
48
+ * The artifacts module is enforced separately, before this function runs.
49
+ */
50
+ export declare function authorize(op: ArtifactOp, meta: Pick<ArtifactMeta, 'owner'> & Partial<Pick<ArtifactMeta, 'group' | 'org'>>, identity: Pick<ArtifactIdentity, 'email'>, access?: ArtifactAccess | null): boolean;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Stateless Streamable HTTP MCP for @hugex/artifact. JSON-RPC 2.0 by hand, no SDK, no CORS.
3
+ */
4
+ import type { ArtifactEnv } from '../types';
5
+ export declare const MAX_BODY_BYTES: number;
6
+ export declare const SERVER_NAME = "hugex-artifact";
7
+ export declare const SERVER_VERSION = "1.0.0";
8
+ export declare const DEFAULT_PROTOCOL_VERSION = "2025-06-18";
9
+ export declare const SUPPORTED_PROTOCOL_VERSIONS: readonly ['2024-11-05', '2025-03-26', '2025-06-18'];
10
+ export type AccessMode = 'phase1' | 'rbac';
11
+ export declare function mcpInstructions(mode: AccessMode): string;
12
+ export declare function handleArtifactMcp(request: Request, env: ArtifactEnv, ctx: ExecutionContext): Promise<Response>;
@@ -0,0 +1,43 @@
1
+ /**
2
+ * MCP tool definitions and handlers for @hugex/artifact.
3
+ * Authorization happens before any mutating RPC. The Durable Object does not authorize.
4
+ */
5
+ import { isSingleSelect } from '../sql';
6
+ import { artifactIndexRpc, artifactRpc } from '../rpc';
7
+ import type { ArtifactEnv } from '../types';
8
+ import { buildArtifactUrl } from '../url';
9
+ export { isSingleSelect };
10
+ export { artifactIndexRpc, artifactRpc, buildArtifactUrl };
11
+ import type { ArtifactIdentity } from './auth';
12
+ import { type ArtifactAccess } from './authz';
13
+ interface ToolDeps {
14
+ env: ArtifactEnv;
15
+ identity: ArtifactIdentity;
16
+ requestUrl: string;
17
+ access: ArtifactAccess | null;
18
+ }
19
+ export interface ToolDefinition {
20
+ name: string;
21
+ description: string;
22
+ inputSchema: {
23
+ type: 'object';
24
+ properties: Record<string, unknown>;
25
+ required?: string[];
26
+ additionalProperties: false;
27
+ };
28
+ }
29
+ export interface ToolTextResult {
30
+ content: [{
31
+ type: 'text';
32
+ text: string;
33
+ }];
34
+ isError?: boolean;
35
+ }
36
+ export declare const ARTIFACT_TOOLS: ToolDefinition[];
37
+ export declare function validateSlug(slug: string): string | null;
38
+ export declare function validateFilePath(path: string): string | null;
39
+ export declare function initialArtifactFiles(title: string): {
40
+ path: string;
41
+ content: string;
42
+ }[];
43
+ export declare function executeTool(name: string, args: Record<string, unknown>, deps: ToolDeps): Promise<ToolTextResult>;
package/dist/rpc.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import type { ArtifactEnv, ArtifactIndexRpc, ArtifactRpc } from "./types";
2
+ /** Stub for the artifact named `slug`. Authorization stays in the caller. */
3
+ export declare function artifactRpc(env: ArtifactEnv, slug: string): ArtifactRpc;
4
+ /** The single tenant index (`idFromName('index')`). */
5
+ export declare function artifactIndexRpc(env: ArtifactEnv): ArtifactIndexRpc;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Source of the `artifact-app.js` module injected into every Dynamic Worker.
3
+ * `server.js` imports `{ ArtifactApp }` from `./artifact-app.js`.
4
+ * The SQL guard is `isSingleSelect` from `sql.ts`, injected as source so the
5
+ * facet and the MCP cannot drift.
6
+ */
7
+ export declare const ARTIFACT_APP_SOURCE: string;
package/dist/sql.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Plain JS of the guard. Injected verbatim into the facet (`artifact-app.js`).
3
+ * It is a string so the bundler cannot rewrite it (esbuild's `__name` helper
4
+ * is not defined inside the Dynamic Worker). The MCP calls `isSingleSelect` below;
5
+ * `sql.test.ts` evals this source and requires the same answers.
6
+ */
7
+ export declare const IS_SINGLE_SELECT_SOURCE = "function isSingleSelect(input) {\n if (typeof input !== \"string\") return false;\n const sql = input;\n let i = 0;\n const n = sql.length;\n\n function skipWsAndComments() {\n while (i < n) {\n const c = sql[i];\n if (c === \" \" || c === \"\\t\" || c === \"\\n\" || c === \"\\r\" || c === \"\\f\") {\n i += 1;\n continue;\n }\n if (c === \"-\" && sql[i + 1] === \"-\") {\n i += 2;\n while (i < n && sql[i] !== \"\\n\") i += 1;\n continue;\n }\n if (c === \"/\" && sql[i + 1] === \"*\") {\n const end = sql.indexOf(\"*/\", i + 2);\n if (end < 0) return false;\n i = end + 2;\n continue;\n }\n return true;\n }\n return true;\n }\n\n if (!skipWsAndComments()) return false;\n if (i >= n || !/^select\\b/i.test(sql.slice(i))) return false;\n i += 6;\n\n let sawSemicolon = false;\n while (i < n) {\n if (sawSemicolon) {\n if (!skipWsAndComments()) return false;\n return i >= n;\n }\n const c = sql[i];\n if (c === \"'\" || c === \"\\\"\" || c === \"`\") {\n const quote = c;\n i += 1;\n let closed = false;\n while (i < n) {\n if (sql[i] === quote) {\n if (sql[i + 1] === quote) {\n i += 2;\n continue;\n }\n i += 1;\n closed = true;\n break;\n }\n i += 1;\n }\n if (!closed) return false;\n continue;\n }\n if (c === \"-\" && sql[i + 1] === \"-\") {\n i += 2;\n while (i < n && sql[i] !== \"\\n\") i += 1;\n continue;\n }\n if (c === \"/\" && sql[i + 1] === \"*\") {\n const end = sql.indexOf(\"*/\", i + 2);\n if (end < 0) return false;\n i = end + 2;\n continue;\n }\n if (c === \";\") {\n sawSemicolon = true;\n i += 1;\n continue;\n }\n i += 1;\n }\n return true;\n}";
8
+ /**
9
+ * One statement, and it must start with SELECT.
10
+ * Leading comments are ignored. A semicolon inside a quote, identifier, or
11
+ * trailing position is not a second statement. WITH is rejected: in SQLite a
12
+ * WITH can end in DELETE, UPDATE, or INSERT.
13
+ * Same behavior as `IS_SINGLE_SELECT_SOURCE`, which the facet runs.
14
+ */
15
+ export declare function isSingleSelect(input: unknown): boolean;
16
+ /** `IS_SINGLE_SELECT_SOURCE` prefixed with `export`, for the facet module. */
17
+ export declare function isSingleSelectSource(): string;
@@ -0,0 +1,7 @@
1
+ import type { ArtifactFile } from "./types";
2
+ /** Initial versions `artifact_create` and `POST /api/internal/artifacts` can publish. */
3
+ export declare const ARTIFACT_TEMPLATES: readonly ["blank", "dashboard", "table", "process-form"];
4
+ export type ArtifactTemplate = (typeof ARTIFACT_TEMPLATES)[number];
5
+ export declare function isArtifactTemplate(value: unknown): value is ArtifactTemplate;
6
+ /** Files of the initial version. `blank` is the default saludo (preact + htm, no server). */
7
+ export declare function templateFiles(template: ArtifactTemplate, title: string): ArtifactFile[];
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Contract shared by the @hugex/artifact runtime (ArtifactDO, ArtifactIndexDO, host routing) and the MCP layer.
3
+ * Owned by the orchestrator: workers must not change these shapes without updating .orchestrator/00-ESTADO.md.
4
+ */
5
+ /** Bindings and vars a tenant worker must provide to mount @hugex/artifact. */
6
+ export interface ArtifactEnv {
7
+ /** Durable Object namespace for ArtifactDO. One instance per artifact, addressed by `idFromName(slug)`. */
8
+ ARTIFACT: DurableObjectNamespace<import('./do/ArtifactDO').ArtifactDO>;
9
+ /** Durable Object namespace for ArtifactIndexDO. Single instance per tenant, `idFromName('index')`. */
10
+ ARTIFACT_INDEX: DurableObjectNamespace<import('./do/ArtifactIndexDO').ArtifactIndexDO>;
11
+ /** worker_loaders binding (Dynamic Workers). */
12
+ LOADER: WorkerLoader;
13
+ /** Tenant id; the JWT `tenant` claim must equal it. */
14
+ TENANT: string;
15
+ /** Production artifact host, e.g. `app-vip.hugex.co`. Optional locally. */
16
+ ARTIFACT_HOST?: string;
17
+ /**
18
+ * Space-separated origins allowed to frame artifact responses, e.g.
19
+ * `https://hugex.co http://localhost:5050 http://127.0.0.1:5052`.
20
+ * Empty or unset → `frame-ancestors 'none'`.
21
+ */
22
+ ARTIFACT_FRAME_ANCESTORS?: string;
23
+ /**
24
+ * Local-only path prefix that mounts the artifact host on the main host, e.g. `/app`.
25
+ * Only set in .dev.vars. Ignored unless the request hostname is `localhost`, `127.0.0.1`, or `[::1]`.
26
+ */
27
+ ARTIFACT_DEV_PATH?: string;
28
+ /** Keycloak RS256 public key (base64 SPKI body, no PEM header), same secret ora already uses. */
29
+ KC_RS256_PK: string;
30
+ /**
31
+ * hx-ora base URL, e.g. `http://localhost:3002`. Together with `HX_API_KEY` this turns on
32
+ * Phase 2: RBAC via `POST /internal/artifacts/access` and index replication via `PUT`.
33
+ * If either is missing, the MCP stays in Phase 1 (owner-only) and the DO does not call hx-ora.
34
+ */
35
+ HX_ORA_URL?: string;
36
+ /** Tenant API key sent as the `Authorization` header to hx-ora internal routes (no `Bearer` prefix). */
37
+ HX_API_KEY?: string;
38
+ }
39
+ export type ArtifactGroup = 'none' | 'all' | (string & {});
40
+ export type VersionState = 'provisional' | 'activa' | 'fallida' | 'anterior';
41
+ export interface ArtifactMeta {
42
+ uuid: string;
43
+ slug: string;
44
+ title: string;
45
+ tenant: string;
46
+ org: string;
47
+ /** Owner email, immutable. */
48
+ owner: string;
49
+ group: ArtifactGroup;
50
+ public: boolean;
51
+ /** Increments on every key rotation. */
52
+ keyGen: number;
53
+ activeVersion: string | null;
54
+ createdAt: string;
55
+ updatedAt: string;
56
+ /**
57
+ * Monotonic index generation. Create stores 1. Promote and settings increment it
58
+ * in the same transaction as the index change. Replicas apply a snapshot only when
59
+ * this value is greater than the stored revision.
60
+ */
61
+ revision: number;
62
+ }
63
+ export interface ArtifactFile {
64
+ path: string;
65
+ content: string;
66
+ }
67
+ /** A file change in artifact_write. `content: null` deletes the path. */
68
+ export interface ArtifactFileChange {
69
+ path: string;
70
+ content: string | null;
71
+ }
72
+ export interface ArtifactVersion {
73
+ /** sha256 hex of the version's file set. */
74
+ id: string;
75
+ runtimeId: string | null;
76
+ author: string;
77
+ message: string;
78
+ state: VersionState;
79
+ createdAt: string;
80
+ error: string | null;
81
+ }
82
+ export interface ArtifactLogEntry {
83
+ ts: string;
84
+ source: 'server' | 'browser' | 'system';
85
+ level: 'debug' | 'info' | 'warn' | 'error';
86
+ message: string;
87
+ version: string | null;
88
+ }
89
+ export interface CreateArtifactInput {
90
+ slug: string;
91
+ title: string;
92
+ tenant: string;
93
+ org: string;
94
+ owner: string;
95
+ }
96
+ export interface WriteInput {
97
+ changes: ArtifactFileChange[];
98
+ message: string;
99
+ /** Must equal the active version id (null only for the first write). */
100
+ baseVersion: string | null;
101
+ author: string;
102
+ }
103
+ export type WriteResult = {
104
+ ok: true;
105
+ version: string;
106
+ state: 'activa';
107
+ warnings: string[];
108
+ } | {
109
+ ok: false;
110
+ code: 'conflict';
111
+ activeVersion: string | null;
112
+ } | {
113
+ ok: false;
114
+ code: 'invalid';
115
+ error: string;
116
+ } | {
117
+ ok: false;
118
+ code: 'limit';
119
+ error: string;
120
+ } | {
121
+ ok: false;
122
+ code: 'failed';
123
+ version: string;
124
+ state: 'fallida';
125
+ error: string;
126
+ };
127
+ export interface SettingsInput {
128
+ group?: ArtifactGroup;
129
+ public?: boolean;
130
+ rotateKey?: boolean;
131
+ }
132
+ export type QueryResult = {
133
+ ok: true;
134
+ rows: Record<string, unknown>[];
135
+ } | {
136
+ ok: false;
137
+ error: string;
138
+ };
139
+ /** Row kept by ArtifactIndexDO so the MCP can list artifacts without waking every ArtifactDO. */
140
+ export interface ArtifactIndexEntry {
141
+ uuid: string;
142
+ slug: string;
143
+ title: string;
144
+ org: string;
145
+ owner: string;
146
+ group: ArtifactGroup;
147
+ public: boolean;
148
+ activeVersion: string | null;
149
+ updatedAt: string;
150
+ /** Same counter as `ArtifactMeta.revision`. Compared with `>`, not with `updatedAt`. */
151
+ revision: number;
152
+ }
153
+ /**
154
+ * RPC surface of ArtifactDO (stub = env.ARTIFACT.get(env.ARTIFACT.idFromName(slug))).
155
+ * Every method throws ArtifactNotFound semantics by returning null / { ok:false } when the DO was never created;
156
+ * see each signature. Authorization is NOT done here: the caller (MCP) authorizes before calling.
157
+ */
158
+ export interface ArtifactRpc {
159
+ /** Creates the artifact. Returns null if this slug already exists. Generates uuid and key. */
160
+ create(input: CreateArtifactInput): Promise<{
161
+ meta: ArtifactMeta;
162
+ key: string;
163
+ } | null>;
164
+ getMeta(): Promise<ArtifactMeta | null>;
165
+ /** Capability for artifact_url: the current key (null when public is true). */
166
+ getAccess(): Promise<{
167
+ public: boolean;
168
+ key: string | null;
169
+ } | null>;
170
+ /** Files of a version (defaults to active). Without `path`, returns the list with content. */
171
+ readFiles(opts?: {
172
+ version?: string;
173
+ path?: string;
174
+ }): Promise<ArtifactFile[] | null>;
175
+ write(input: WriteInput): Promise<WriteResult>;
176
+ /** Re-activates an older version's code (data is untouched). Same result shape as write. */
177
+ rollback(input: {
178
+ version: string;
179
+ author: string;
180
+ }): Promise<WriteResult>;
181
+ settings(input: SettingsInput): Promise<{
182
+ meta: ArtifactMeta;
183
+ key: string | null;
184
+ } | null>;
185
+ versions(opts?: {
186
+ limit?: number;
187
+ }): Promise<ArtifactVersion[] | null>;
188
+ logs(opts?: {
189
+ limit?: number;
190
+ source?: ArtifactLogEntry['source'];
191
+ }): Promise<ArtifactLogEntry[] | null>;
192
+ query(sql: string): Promise<QueryResult>;
193
+ /** Removes the artifact, index row, and hx-ora tombstone. Returns null if the slug was never created. */
194
+ delete(input: {
195
+ author: string;
196
+ }): Promise<{
197
+ ok: true;
198
+ oraSyncFailed?: boolean;
199
+ } | null>;
200
+ }
201
+ /** RPC surface of ArtifactIndexDO (stub = env.ARTIFACT_INDEX.get(env.ARTIFACT_INDEX.idFromName('index'))). */
202
+ export interface ArtifactIndexRpc {
203
+ put(entry: ArtifactIndexEntry): Promise<void>;
204
+ remove(slug: string): Promise<void>;
205
+ get(slug: string): Promise<ArtifactIndexEntry | null>;
206
+ list(opts?: {
207
+ owner?: string;
208
+ }): Promise<ArtifactIndexEntry[]>;
209
+ }
210
+ /**
211
+ * Headers the host router sets when forwarding a browser request to ArtifactDO.fetch().
212
+ * The DO never trusts anything else from the client for access decisions.
213
+ */
214
+ export declare const HX_HEADER_KEY = "x-hx-artifact-key";
215
+ /** Public base path of the artifact including trailing slash, e.g. `/demo/k/abc/` or `/app/demo/`. */
216
+ export declare const HX_HEADER_BASE = "x-hx-artifact-base";
package/dist/url.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ export declare function buildArtifactUrl(input: {
2
+ requestUrl: string;
3
+ host?: string;
4
+ devPath?: string;
5
+ slug: string;
6
+ isPublic: boolean;
7
+ key: string | null;
8
+ }): string | null;
@@ -0,0 +1,23 @@
1
+ /** Total length 2..48. First char is alphanumeric; the rest may include `-`. */
2
+ export declare const SLUG_RE: RegExp;
3
+ export declare const RESERVED_SLUGS: Set<string>;
4
+ /** Returns an error string, or null when the slug is acceptable. */
5
+ export declare function validateSlug(slug: string): string | null;
6
+ /**
7
+ * Relative file path inside an artifact.
8
+ * Rejects `..`, a leading `/`, backslashes, empty segments, and paths over 200 chars.
9
+ */
10
+ export declare function validateFilePath(path: string): string | null;
11
+ export type ArtifactTheme = "hugex" | "none";
12
+ export type ArtifactManifest = {
13
+ title: string;
14
+ libs: string[];
15
+ theme: ArtifactTheme;
16
+ };
17
+ export declare function parseArtifactManifest(text: string): {
18
+ ok: true;
19
+ manifest: ArtifactManifest;
20
+ } | {
21
+ ok: false;
22
+ error: string;
23
+ };
@@ -0,0 +1,2 @@
1
+ /** Package version mixed into `runtimeId`. Bump when the Dynamic Worker contract changes. */
2
+ export declare const ARTIFACT_PKG_VERSION = "0.1.0";
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "@hugex/artifact",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "HugeX Artifacts runtime for Cloudflare Workers",
5
+ "author": "a@hugex.co",
6
+ "license": "SEE LICENSE IN LICENSE",
7
+ "type": "module",
8
+ "dependencies": {
9
+ "jose": "^6.2.3"
10
+ },
11
+ "publishConfig": {
12
+ "access": "public"
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md",
17
+ "LICENSE"
18
+ ],
19
+ "main": "./dist/index.js",
20
+ "module": "./dist/index.js",
21
+ "types": "./dist/index.d.ts",
22
+ "exports": {
23
+ ".": {
24
+ "import": "./dist/index.js",
25
+ "types": "./dist/index.d.ts"
26
+ }
27
+ }
28
+ }