@jini-ai/platform 0.6.22 → 0.7.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.
Files changed (38) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/dist/fetch-with-timeout.d.ts +0 -1
  3. package/dist/fetch-with-timeout.js +2 -3
  4. package/dist/fs/backup-once.d.ts +8 -0
  5. package/dist/fs/backup-once.js +11 -0
  6. package/dist/fs/index.d.ts +1 -0
  7. package/dist/fs/index.js +1 -0
  8. package/dist/http/guarded/client.js +4 -4
  9. package/dist/http/guarded/transport.fetch.js +6 -5
  10. package/dist/mail/adapter-module.d.ts +2 -29
  11. package/dist/mail/engine-contracts.d.ts +1 -128
  12. package/dist/mail/index.d.ts +3 -0
  13. package/dist/mail/index.js +3 -0
  14. package/dist/mail/plugin-abi.d.ts +16 -0
  15. package/dist/mail/plugin-abi.js +21 -0
  16. package/dist/mail/ports.d.ts +1 -91
  17. package/dist/mail/provider-mailer.d.ts +12 -0
  18. package/dist/mail/provider-mailer.js +31 -0
  19. package/dist/mail/provider-setup.d.ts +33 -0
  20. package/dist/mail/provider-setup.js +144 -0
  21. package/dist/mail/provider.d.ts +2 -90
  22. package/dist/mail/types.d.ts +1 -110
  23. package/dist/net/endpoint-policy.d.ts +6 -0
  24. package/dist/net/endpoint-policy.js +9 -0
  25. package/dist/object-store/descriptors.d.ts +32 -0
  26. package/dist/object-store/descriptors.js +79 -0
  27. package/dist/object-store/index.d.ts +1 -0
  28. package/dist/object-store/index.js +1 -0
  29. package/dist/secrets/credential-sets/types.d.ts +1 -73
  30. package/dist/secrets/credential-sets/types.js +0 -4
  31. package/dist/secrets/credential-sets/vault.types.d.ts +3 -147
  32. package/dist/secrets/ports.d.ts +1 -32
  33. package/dist/secrets/types.d.ts +1 -9
  34. package/dist/web/index.d.ts +1 -0
  35. package/dist/web/index.js +1 -0
  36. package/dist/web/strip-html-presentation.d.ts +15 -0
  37. package/dist/web/strip-html-presentation.js +60 -0
  38. package/package.json +2 -2
@@ -0,0 +1,144 @@
1
+ /**
2
+ * @file The declarative setup metadata a mail plugin may ship in its mail-adapters file's v2
3
+ * descriptor (`setup: { helpUrl?, fields?: [...] }`): field labels, input types, non-secret
4
+ * defaults (an API origin, a preset server endpoint) and help links. Core renders whatever the
5
+ * plugin declares and never branches on a provider id — a vendor's know-how ships in its plugin.
6
+ *
7
+ * Absent `setup` (every descriptor written before 2026-10-22), {@link defaultMailProviderSetup}
8
+ * derives plain fields from `credentialKeys`, so an older plugin still gets a usable form.
9
+ */
10
+ const FIELD_TYPES = ["secret", "text", "url", "email"];
11
+ const MAX_TEXT = 300;
12
+ /** The generic field each credential key gets when the plugin declares nothing more specific. */
13
+ const DEFAULT_FIELDS = {
14
+ token: { key: "token", label: "API key", type: "secret", required: true },
15
+ username: { key: "username", label: "Username", type: "text", required: true },
16
+ baseUrl: { key: "baseUrl", label: "API base URL", type: "url", required: true },
17
+ };
18
+ /**
19
+ * Plain fields for each declared credential key, plus `baseUrl`: the credential store files every
20
+ * key under an origin, so the form always asks for one. An unknown key becomes a required text field.
21
+ * @complexity O(k) keys.
22
+ */
23
+ export function defaultMailProviderSetup(required, _optional = {}) {
24
+ return { fields: storedKeys(required.credentialKeys).map((key) => DEFAULT_FIELDS[key] ?? { key, label: key, type: "text", required: true }) };
25
+ }
26
+ /** The credential keys a saved key actually has: the declared ones plus `baseUrl`. @complexity O(k). */
27
+ function storedKeys(credentialKeys, _options = {}) {
28
+ return [...new Set([...credentialKeys, "baseUrl"])];
29
+ }
30
+ /**
31
+ * Parses a descriptor's optional `setup`. Pure. `undefined` stays undefined (use the default).
32
+ * A field's `key` must be one of the provider's credential keys or `baseUrl` (always stored), and
33
+ * `token` must be a secret field, so a plugin cannot turn the key input into plain text.
34
+ * @returns The setup, or the reason it is invalid (the whole descriptor is then refused).
35
+ * @complexity O(f) fields.
36
+ */
37
+ export function parseMailProviderSetup(required, _optional = {}) {
38
+ const { value, at } = required;
39
+ if (value === undefined)
40
+ return undefined;
41
+ if (!isRecord(value))
42
+ return `${at}.setup must be an object`;
43
+ const helpUrl = optionalHttpsUrl({ value: value.helpUrl });
44
+ if (helpUrl === null)
45
+ return `${at}.setup.helpUrl must be an https URL`;
46
+ const fields = parseFields({ value: value.fields ?? [], at, allowed: new Set(storedKeys(required.credentialKeys)) });
47
+ if (typeof fields === "string")
48
+ return fields;
49
+ const declared = new Set(fields.map((field) => field.key));
50
+ // Undeclared keys keep their plain default field, so a partial `setup` never drops an input.
51
+ const missing = defaultMailProviderSetup({ credentialKeys: required.credentialKeys }).fields.filter((field) => !declared.has(field.key));
52
+ return { fields: [...fields, ...missing], ...(helpUrl ? { helpUrl } : {}) };
53
+ }
54
+ /** The declared fields in order, or why one is invalid. @complexity O(f^2) for tiny f. */
55
+ function parseFields(required, _options = {}) {
56
+ const { value, at } = required;
57
+ if (!Array.isArray(value))
58
+ return `${at}.setup.fields must be an array`;
59
+ const fields = [];
60
+ for (const [index, entry] of value.entries()) {
61
+ const field = parseField({ entry, at: `${at}.setup.fields[${index}]`, allowed: required.allowed });
62
+ if (typeof field === "string")
63
+ return field;
64
+ if (fields.some((seen) => seen.key === field.key))
65
+ return `${at}.setup.fields[${index}].key '${field.key}' is declared twice`;
66
+ fields.push(field);
67
+ }
68
+ return fields;
69
+ }
70
+ /**
71
+ * The descriptor property form of {@link parseMailProviderSetup}: `{}` when absent, `{setup}` when
72
+ * valid, else the reason. @complexity O(f) fields.
73
+ */
74
+ export function parseMailProviderSetupProperty(required, _optional = {}) {
75
+ const setup = parseMailProviderSetup(required);
76
+ if (typeof setup === "string")
77
+ return setup;
78
+ return setup ? { setup } : {};
79
+ }
80
+ /** One field entry, or why it is invalid. @complexity O(1). */
81
+ function parseField(required, _options = {}) {
82
+ const { entry, at } = required;
83
+ if (!isRecord(entry))
84
+ return `${at} must be an object`;
85
+ const head = parseFieldHead({ entry, at, allowed: required.allowed });
86
+ if (typeof head === "string")
87
+ return head;
88
+ const text = optionalTexts(entry, ["defaultValue", "placeholder", "help"]);
89
+ if (typeof text === "string")
90
+ return `${at}.${text} must be a non-empty string`;
91
+ const helpUrl = optionalHttpsUrl({ value: entry.helpUrl });
92
+ if (helpUrl === null)
93
+ return `${at}.helpUrl must be an https URL`;
94
+ // A secret has no default: a default would be a secret shipped in a public plugin manifest.
95
+ if (head.type === "secret" && text.defaultValue !== undefined)
96
+ return `${at}.defaultValue is not allowed on a secret field`;
97
+ return { ...head, required: entry.required !== false, ...text, ...(helpUrl ? { helpUrl } : {}) };
98
+ }
99
+ /** A field's key, label and type, or why they are invalid. @complexity O(1). */
100
+ function parseFieldHead(required, _options = {}) {
101
+ const { entry, at } = required;
102
+ if (typeof entry.key !== "string" || !required.allowed.has(entry.key))
103
+ return `${at}.key must be one of the provider's credential keys or baseUrl`;
104
+ if (!isText(entry.label))
105
+ return `${at}.label must be a non-empty string`;
106
+ const type = entry.type ?? "text";
107
+ if (!FIELD_TYPES.includes(type))
108
+ return `${at}.type must be one of ${FIELD_TYPES.join(", ")}`;
109
+ if (entry.key === "token" && type !== "secret")
110
+ return `${at}: the token field must be type secret`;
111
+ return { key: entry.key, label: entry.label.trim(), type: type };
112
+ }
113
+ /** The present optional strings, or the name of the first malformed one. @complexity O(n) names. */
114
+ function optionalTexts(entry, names) {
115
+ const out = {};
116
+ for (const name of names) {
117
+ if (entry[name] === undefined)
118
+ continue;
119
+ if (!isText(entry[name]))
120
+ return name;
121
+ out[name] = entry[name].trim();
122
+ }
123
+ return out;
124
+ }
125
+ /** undefined when absent, null when malformed, else the URL. @complexity O(1). */
126
+ function optionalHttpsUrl({ value }, _options = {}) {
127
+ if (value === undefined)
128
+ return undefined;
129
+ if (typeof value !== "string")
130
+ return null;
131
+ try {
132
+ return new URL(value).protocol === "https:" ? value : null;
133
+ }
134
+ catch {
135
+ return null;
136
+ }
137
+ }
138
+ function isText(value) {
139
+ return typeof value === "string" && value.trim() !== "" && value.length <= MAX_TEXT;
140
+ }
141
+ function isRecord(value) {
142
+ return typeof value === "object" && value !== null && !Array.isArray(value);
143
+ }
144
+ //# sourceMappingURL=provider-setup.js.map
@@ -1,89 +1,14 @@
1
- /**
2
- * @file Mail provider contract + keyed registry (email provider contract v1, 2026-10-21).
3
- *
4
- * A provider is a {@link MailAdapterModule} that also names itself, declares the credential fields
5
- * it needs and its capabilities, and optionally parses delivery feedback and reports what a sending
6
- * domain must publish (SPF/DKIM/DMARC). Selection is explicit: the host stores
7
- * `mail.provider.{transactional,bulk}` and never picks "the first provider with a credential".
8
- */
9
- import { type DomainRequirement, type ProviderContext, type ProviderRegistry, type ProviderResult } from "@jini-ai/core/provider-registry";
10
- import type { HttpClientPort } from "@jini-ai/core/primitives";
11
- import type { MailAdapterCredential, MailAdapterModule } from "./adapter-module.js";
12
- import type { MailDeliveryLane } from "./ports.js";
13
- import type { MailerFeedbackEvent } from "./types.js";
14
- /** Provider token bucket: sustained rate plus burst. Absent = no provider-declared limit. */
15
- export interface MailRateLimit {
16
- readonly perSecond: number;
17
- readonly burst: number;
18
- }
19
- export interface MailProviderCapabilities {
20
- /** False for local drivers (console): they never count as real delivery. */
21
- readonly hosted: boolean;
22
- /** True exactly when the module ships a {@link MailFeedbackParser}. */
23
- readonly feedback: boolean;
24
- /** True exactly when the module implements domainRequirements + domainStatus. */
25
- readonly domainVerification: boolean;
26
- readonly rateLimit?: MailRateLimit;
27
- }
28
- export interface MailFeedbackParser {
29
- /** Raw bytes in; never throws. Any of `secrets` may match so a webhook secret can rotate. */
30
- verify(required: {
31
- rawBody: Uint8Array;
32
- headers: Readonly<Record<string, string>>;
33
- secrets: readonly string[];
34
- now: number;
35
- }): boolean;
36
- /** Headers are passed so a parser can key events on a delivery id (e.g. `svix-id`).
37
- * Each event must carry eventId + recipient, or the ingest drops it (no dedup key, no suppression key). */
38
- parse(required: {
39
- rawBody: Uint8Array;
40
- workspaceId: string;
41
- headers: Readonly<Record<string, string>>;
42
- }): readonly MailerFeedbackEvent[] | {
43
- error: string;
44
- };
45
- }
46
- /** Per-call context: who the call acts for plus the host-resolved credential and guarded HTTP. */
47
- export interface MailProviderCallContext extends ProviderContext {
48
- readonly credential: MailAdapterCredential;
49
- readonly httpClient: HttpClientPort;
50
- }
51
- export type MailDomainState = "verified" | "pending" | "failed" | "not_found";
52
- export interface MailProviderModule extends MailAdapterModule {
53
- readonly id: string;
54
- readonly label: string;
55
- /** Credential fields the host must resolve (e.g. `token`, `username`, `baseUrl`). */
56
- readonly credentialKeys: readonly string[];
57
- /** Separate vault key for the webhook signing secret, so it rotates independently of the API key. */
58
- readonly webhookSecretKey?: string;
59
- readonly capabilities: MailProviderCapabilities;
60
- readonly feedback?: MailFeedbackParser;
61
- /** DNS records the provider needs before it will send as `domain`; satisfied through the DNS port. */
62
- domainRequirements?(ctx: MailProviderCallContext, required: {
63
- domain: string;
64
- }): Promise<ProviderResult<DomainRequirement>>;
65
- domainStatus?(ctx: MailProviderCallContext, required: {
66
- domain: string;
67
- }): Promise<ProviderResult<{
68
- domain: string;
69
- state: MailDomainState;
70
- }>>;
71
- }
1
+ import type { MailDomainState, MailProviderModule, MailProviderRegistry, MailProviderSetting, MailStatus } from '@jini-ai/core/contracts/mail';
2
+ export type { MailRateLimit, MailProviderCapabilities, MailFeedbackParser, MailProviderCallContext, MailDomainState, MailProviderModule, MailProviderRegistry, MailProviderSetting, MailLaneState, MailLaneStatus, MailStatusWarning, MailStatus } from '@jini-ai/core/contracts/mail';
72
3
  /** Shape check run by the registry for core and plugin registrations. @complexity O(k) keys. */
73
4
  export declare function validateMailProvider({ provider }: {
74
5
  provider: MailProviderModule;
75
6
  }): string | undefined;
76
- export type MailProviderRegistry = ProviderRegistry<MailProviderModule>;
77
7
  /** Mail registry over the shared keyed registry; built-ins throw on a bad registration, plugins are refused. */
78
8
  export declare function createMailProviderRegistry(_required?: Record<string, never>, optional?: {
79
9
  builtins?: readonly MailProviderModule[];
80
10
  }): MailProviderRegistry;
81
11
  export declare const MAIL_PROVIDER_SETTING_KEY = "mail.provider";
82
- /** One provider per lane; equal ids today, separable later without a data migration. null = unconfigured. */
83
- export interface MailProviderSetting {
84
- readonly transactional: string | null;
85
- readonly bulk: string | null;
86
- }
87
12
  /**
88
13
  * The value written on first boot: whatever the host was effectively using, so a live site never
89
14
  * silently switches provider when selection becomes explicit. A local driver (console) or nothing
@@ -93,19 +18,6 @@ export declare function initialMailProviderSetting(_required: Record<string, nev
93
18
  effectiveProviderId?: string | null;
94
19
  registry?: MailProviderRegistry;
95
20
  }): MailProviderSetting;
96
- export type MailLaneState = "ready" | "unconfigured" | "unknown_provider" | "missing_credential" | "local_only";
97
- export interface MailLaneStatus {
98
- readonly lane: MailDeliveryLane;
99
- readonly providerId: string | null;
100
- readonly state: MailLaneState;
101
- }
102
- export type MailStatusWarning = "sender_unverified" | "sender_unknown";
103
- export interface MailStatus {
104
- /** `unconfigured` drives the blocking admin banner; owner sign-in must never depend on mail. */
105
- readonly state: "ready" | "unconfigured" | "degraded";
106
- readonly lanes: readonly MailLaneStatus[];
107
- readonly warnings: readonly MailStatusWarning[];
108
- }
109
21
  /** Pure status projection for `mail_status` and the admin banner. @complexity O(lanes). */
110
22
  export declare function computeMailStatus(required: {
111
23
  setting: MailProviderSetting;
@@ -1,111 +1,2 @@
1
- import type { ISODateTime, UUID } from "@jini-ai/core/primitives";
2
- export interface OutboundEmail {
3
- workspaceId: UUID;
4
- to: EmailAddress;
5
- from: EmailAddress;
6
- replyTo?: EmailAddress;
7
- subject: string;
8
- /** At least one of html/text must be supplied; the transport does not render missing content. */
9
- html?: string;
10
- /** A plain-text alternative improves accessibility and deliverability. */
11
- text?: string;
12
- /** Allows caller-owned List-Unsubscribe and RFC 8058 one-click headers without provider coupling. */
13
- headers?: Readonly<Record<string, string>>;
14
- /** Additive/optional for existing consumers; content is base64 so no live stream/path crosses the ABI. */
15
- attachments?: readonly EmailAttachment[];
16
- }
17
- export interface EmailAddress {
18
- email: string;
19
- name?: string;
20
- }
21
- export interface EmailAttachment {
22
- filename: string;
23
- contentType: string;
24
- contentBase64: string;
25
- }
26
- export interface MailerSendOptions {
27
- /** Redelivery must reuse this identity; generating a new key defeats outbox deduplication. */
28
- idempotencyKey: string;
29
- /** Scope suppression and send dedup to the same delivery boundary. */
30
- workspaceId: UUID;
31
- /** Preserve provenance so delivery feedback can be attributed to the originating campaign/module. */
32
- sourceContext: {
33
- module: string;
34
- ref?: string;
35
- };
36
- timeoutMs?: number;
37
- purpose?: "transactional" | "bulk" | `feature:${string}`;
38
- /** Keep interaction separate from notification readiness: a shared transactional purpose cannot
39
- * distinguish them. Unmapped/absent lanes resolve to notification rather than opening the
40
- * interactive bypass; the caller-facing facade applies that fail-closed allowlist. */
41
- lane?: "interactive" | "notification";
42
- /** Configuration facts approved by the caller, rechecked immediately before delivery. */
43
- mailTestApproval?: MailTestApproval;
44
- }
45
- /** Serializable outcomes cross the adapter ABI; live thrown objects cannot be carried as results. */
46
- export type MailerSendResult = {
47
- ok: true;
48
- providerMessageId: string;
49
- acceptedAt: ISODateTime;
50
- } | {
51
- ok: false;
52
- retryable: boolean;
53
- errorCode: string;
54
- message: string;
55
- /** The provider may have accepted the message (timeout after submit, crash mid-send): never
56
- * auto-retry under a new identity; the send ledger records the outcome as `unknown`. */
57
- unknown?: boolean;
58
- /** Rate-limit hint (provider 429 or the local token bucket); absent means "caller's backoff". */
59
- retryAfterMs?: number;
60
- };
61
- export interface MailerCapabilities {
62
- driver: string;
63
- supportsIdempotencyKey: boolean;
64
- supportsWebhookFeedback: boolean;
65
- /** A limit of one means sequential send fallback, not an optional batch method consumers branch on. */
66
- maxBatchSize: number;
67
- /** Required attachments must be refused when unsupported, never dropped while reporting success. */
68
- supportsAttachments: boolean;
69
- }
70
- export interface MailerFeedbackEvent {
71
- workspaceId: UUID;
72
- providerMessageId: string;
73
- sourceContext: {
74
- module: string;
75
- ref?: string;
76
- };
77
- kind: "delivered" | "bounced" | "complained";
78
- /** Provider event id: the inbox dedups replays on (providerId, eventId). Optional for v1 parsers. */
79
- eventId?: string;
80
- /** Lower-cased recipient address; suppression needs it, provider message ids alone cannot key it. */
81
- recipient?: string;
82
- hardBounce: boolean;
83
- occurredAt: ISODateTime;
84
- }
85
- /** Required delivery identity/provenance belongs in the first argument of every send. */
86
- export type MailerDelivery = Pick<MailerSendOptions, "idempotencyKey" | "workspaceId" | "sourceContext">;
87
- export type MailerOptional = Omit<MailerSendOptions, keyof MailerDelivery>;
88
- export type MailerSendRequired = MailerDelivery & {
89
- message: OutboundEmail;
90
- };
91
- export type MailerBatchRequired = MailerDelivery & {
92
- messages: readonly OutboundEmail[];
93
- };
94
- /** Persisted test-mode shape; capture availability is decided separately by the delivery wrapper. */
95
- export type MailTestModeSetting = {
96
- mode: "off";
97
- } | {
98
- mode: "redirect";
99
- to: string;
100
- } | {
101
- mode: "capture";
102
- };
103
- /** Preserve field order when constructing/comparing approvals: approval bytes are caller-owned. */
104
- export interface MailTestApproval {
105
- providerId: string | null;
106
- driver: string;
107
- from: OutboundEmail["from"];
108
- mode: MailTestModeSetting["mode"];
109
- effectiveRecipient: string;
110
- }
1
+ export type * from '@jini-ai/core/contracts/mail';
111
2
  //# sourceMappingURL=types.d.ts.map
@@ -30,4 +30,10 @@ export declare function isLoopbackApiHost({ hostname }: {
30
30
  export declare function isBlockedExternalApiHostname({ hostname }: {
31
31
  hostname: string;
32
32
  }): boolean;
33
+ /** Literal policy for a hostname from a deployed endpoint URL: local names and reserved
34
+ * addresses are excluded. DNS reachability remains the deployment host's responsibility.
35
+ * @complexity O(hostname length), no DNS or other I/O. */
36
+ export declare function isDeployedApiHostname({ hostname }: {
37
+ hostname: string;
38
+ }, _optional?: Record<string, never>): boolean;
33
39
  //# sourceMappingURL=endpoint-policy.d.ts.map
@@ -206,4 +206,13 @@ export function isBlockedExternalApiHostname({ hostname }) {
206
206
  const addressClass = classifyAddressLiteral({ address: host });
207
207
  return addressClass !== null && addressClass !== 'public' && addressClass !== 'loopback';
208
208
  }
209
+ /** Literal policy for a hostname from a deployed endpoint URL: local names and reserved
210
+ * addresses are excluded. DNS reachability remains the deployment host's responsibility.
211
+ * @complexity O(hostname length), no DNS or other I/O. */
212
+ export function isDeployedApiHostname({ hostname }, _optional = {}) {
213
+ const host = normalizeBracketedIpv6(hostname);
214
+ if (isLoopbackApiHost({ hostname: host }) || isBlockedExternalApiHostname({ hostname: host }))
215
+ return false;
216
+ return !host.endsWith('.localhost') && !host.endsWith('.local');
217
+ }
209
218
  //# sourceMappingURL=endpoint-policy.js.map
@@ -0,0 +1,32 @@
1
+ export interface ObjectStoreEnvDeclaration {
2
+ readonly providerId: string;
3
+ readonly selector: string;
4
+ readonly settings: Readonly<Record<string, string>>;
5
+ readonly credentialFields: Readonly<Record<string, string>>;
6
+ readonly secret: string;
7
+ readonly required: readonly string[];
8
+ }
9
+ /** One provider entry; structurally the lifecycle's provider-contribution descriptor plus `env`. */
10
+ export interface ObjectStoreDescriptor {
11
+ readonly id: string;
12
+ /** Plain-JS module inside the plugin root (`.mjs`); containment is checked on disk at import. */
13
+ readonly module: string;
14
+ readonly label?: string;
15
+ readonly env?: Omit<ObjectStoreEnvDeclaration, "providerId">;
16
+ }
17
+ export type ObjectStoresParseResult = {
18
+ readonly ok: true;
19
+ readonly descriptors: readonly ObjectStoreDescriptor[];
20
+ } | {
21
+ readonly ok: false;
22
+ readonly reason: string;
23
+ };
24
+ /**
25
+ * Parses a plugin's object-stores file: `{ schemaVersion: 1, providers: [{ id, module, label? }] }`. Ids
26
+ * are checked against the shared grammar by the loader before any module is imported.
27
+ * @complexity O(n) entries.
28
+ */
29
+ export declare function parseObjectStoresFile(required: {
30
+ readonly raw: string;
31
+ }, _optional?: Record<string, never>): ObjectStoresParseResult;
32
+ //# sourceMappingURL=descriptors.d.ts.map
@@ -0,0 +1,79 @@
1
+ /**
2
+ * @file The pure half of the object-stores Agent Plugin contribution: the descriptor parser and the
3
+ * operator env declarations a provider may carry. The host names the file and loads each module
4
+ * through its lifecycle, validating it with `objectStoreProviderFault` from `@jini-ai/core/object-store`.
5
+ */
6
+ import path from "node:path";
7
+ const MAX_LABEL_LENGTH = 100;
8
+ /**
9
+ * Parses a plugin's object-stores file: `{ schemaVersion: 1, providers: [{ id, module, label? }] }`. Ids
10
+ * are checked against the shared grammar by the loader before any module is imported.
11
+ * @complexity O(n) entries.
12
+ */
13
+ export function parseObjectStoresFile(required, _optional = {}) {
14
+ let value;
15
+ try {
16
+ value = JSON.parse(required.raw);
17
+ }
18
+ catch {
19
+ return { ok: false, reason: "not valid JSON" };
20
+ }
21
+ if (!isPlainObject(value) || value.schemaVersion !== 1)
22
+ return { ok: false, reason: "schemaVersion must be 1" };
23
+ if (!Array.isArray(value.providers))
24
+ return { ok: false, reason: "providers must be an array" };
25
+ const descriptors = [];
26
+ for (const [index, entry] of value.providers.entries()) {
27
+ const result = parseDescriptor({ entry, at: `providers[${index}]` });
28
+ if (typeof result === "string")
29
+ return { ok: false, reason: result };
30
+ if (descriptors.some((seen) => seen.id === result.id))
31
+ return { ok: false, reason: `providers[${index}].id '${result.id}' is declared twice` };
32
+ descriptors.push(result);
33
+ }
34
+ return { ok: true, descriptors };
35
+ }
36
+ /** One manifest entry, or why it is malformed. @complexity O(1). */
37
+ function parseDescriptor({ entry, at }, _optional = {}) {
38
+ if (!isPlainObject(entry))
39
+ return `${at} must be an object`;
40
+ const { id, label, module } = entry;
41
+ if (typeof id !== "string")
42
+ return `${at}.id must be a string`;
43
+ if (typeof module !== "string" || !module.endsWith(".mjs") || path.posix.isAbsolute(module))
44
+ return `${at}.module must be a relative path ending in .mjs`;
45
+ const extra = descriptorMetadata({ label, env: entry.env, at });
46
+ if (typeof extra === "string")
47
+ return extra;
48
+ return { id, module, ...extra };
49
+ }
50
+ /** Optional metadata shares the provider declaration's validation and refusal policy. */
51
+ function descriptorMetadata({ label, env, at }, _optional = {}) {
52
+ if (label !== undefined && (typeof label !== "string" || label.trim() === "" || label.length > MAX_LABEL_LENGTH))
53
+ return `${at}.label must be a non-empty string of at most ${MAX_LABEL_LENGTH} characters`;
54
+ if (env !== undefined && !validEnvDeclaration({ value: env }))
55
+ return `${at}.env must declare a selector, env maps, secret and ordered required variables`;
56
+ return { ...(label === undefined ? {} : { label: label }), ...(env === undefined ? {} : { env: env }) };
57
+ }
58
+ function isPlainObject(value) {
59
+ return typeof value === "object" && value !== null && !Array.isArray(value);
60
+ }
61
+ function envMap(value) {
62
+ return isPlainObject(value) && Object.values(value).every(envName);
63
+ }
64
+ function envName(value) {
65
+ return typeof value === "string" && /^[A-Z][A-Z0-9_]*$/.test(value);
66
+ }
67
+ function envSelector(value) {
68
+ return typeof value === "string" && /^[a-z][a-z0-9-]*$/.test(value) && value !== "local";
69
+ }
70
+ function validEnvDeclaration({ value }, _optional = {}) {
71
+ if (!isPlainObject(value))
72
+ return false;
73
+ if (!envSelector(value.selector))
74
+ return false;
75
+ if (!envMap(value.settings) || !envMap(value.credentialFields) || !envName(value.secret))
76
+ return false;
77
+ return Array.isArray(value.required) && value.required.length > 0 && value.required.every(envName);
78
+ }
79
+ //# sourceMappingURL=descriptors.js.map
@@ -1,2 +1,3 @@
1
1
  export { createLocalFsObjectStore, createLocalFsObjectStoreProvider } from './local-fs.js';
2
+ export * from './descriptors.js';
2
3
  //# sourceMappingURL=index.d.ts.map
@@ -1,2 +1,3 @@
1
1
  export { createLocalFsObjectStore, createLocalFsObjectStoreProvider } from './local-fs.js';
2
+ export * from './descriptors.js';
2
3
  //# sourceMappingURL=index.js.map
@@ -1,74 +1,2 @@
1
- /** Host-neutral credential records and workspace-scoped repository contracts.
2
- * insert/update clear other defaults in the same vendor group; deleting a default promotes
3
- * the most recently updated remaining row. Summaries never include sealed payloads.
4
- */
5
- import type { SealedSecret } from "../types.js";
6
- export interface VendorCredentialSetRecord {
7
- readonly workspaceId: string;
8
- readonly id: string;
9
- /** Open string so plugin hosts can declare vendors beyond the built-in validators. */
10
- readonly vendorId: string;
11
- /** Optional only for historical DTO producers; unified vault metadata requires this subtype. */
12
- readonly credentialType?: "vendor";
13
- /** Explicit compatibility IDs, independent of label; omitted by historical DTO producers. */
14
- readonly worksFor?: readonly string[];
15
- readonly label: string;
16
- readonly sealed: SealedSecret;
17
- /** Last four secret characters for recognition, stored in clear; a suffix alone is not the token. */
18
- readonly tokenTail: string;
19
- /** At most one default per (workspaceId, vendorId), maintained by the store/repository write path. */
20
- readonly isDefault: boolean;
21
- /** Only a verified public login belongs here; null until verification populates it. */
22
- readonly accountLabel: string | null;
23
- readonly createdAt: string;
24
- readonly updatedAt: string;
25
- }
26
- export interface VendorCredentialSetSummary {
27
- readonly id: string;
28
- readonly vendorId: string;
29
- /** Optional for compatibility with historical summaries. */
30
- readonly credentialType?: "vendor";
31
- readonly worksFor?: readonly string[];
32
- readonly label: string;
33
- readonly configured: true;
34
- readonly isDefault: boolean;
35
- readonly tokenTail: string;
36
- readonly accountLabel: string | null;
37
- readonly createdAt: string;
38
- readonly updatedAt: string;
39
- }
40
- export interface VendorCredentialSetRepoPort {
41
- insert(record: VendorCredentialSetRecord): Promise<void>;
42
- /** Full-row replacement supports rename and secret rotation; label uniqueness can still reject it. */
43
- update(record: VendorCredentialSetRecord): Promise<void>;
44
- findById(input: {
45
- workspaceId: string;
46
- id: string;
47
- }): Promise<VendorCredentialSetRecord | null>;
48
- findDefaultByVendor(input: {
49
- workspaceId: string;
50
- vendorId: string;
51
- }): Promise<VendorCredentialSetRecord | null>;
52
- /** Lets the store recognize a group's first row and choose a promotion candidate before deletion. */
53
- listByVendor(input: {
54
- workspaceId: string;
55
- vendorId: string;
56
- }): Promise<VendorCredentialSetRecord[]>;
57
- /** Intentionally unpaginated for a human-managed connection list, rather than a bulk credential inventory. */
58
- listByWorkspace(input: {
59
- workspaceId: string;
60
- }): Promise<VendorCredentialSetRecord[]>;
61
- /** Missing (workspaceId, id) is a no-op so repeated deletes remain idempotent. */
62
- delete(input: {
63
- workspaceId: string;
64
- id: string;
65
- }): Promise<void>;
66
- /** Target only accountLabel: verification must not rewrite sealed/default/tail/updatedAt state.
67
- * A missing row is a no-op, as with delete. */
68
- updateAccountLabel(input: {
69
- workspaceId: string;
70
- id: string;
71
- accountLabel: string;
72
- }): Promise<void>;
73
- }
1
+ export type * from '@jini-ai/core/contracts/vault';
74
2
  //# sourceMappingURL=types.d.ts.map
@@ -1,6 +1,2 @@
1
- /** Host-neutral credential records and workspace-scoped repository contracts.
2
- * insert/update clear other defaults in the same vendor group; deleting a default promotes
3
- * the most recently updated remaining row. Summaries never include sealed payloads.
4
- */
5
1
  export {};
6
2
  //# sourceMappingURL=types.js.map