import * as kms from "@distilled.cloud/aws/kms";
import * as ssm from "@distilled.cloud/aws/ssm";
import { Unowned } from "alchemy/AdoptPolicy";
import { isResolved } from "alchemy/Diff";
import { createPhysicalName } from "alchemy/PhysicalName";
import * as Provider from "alchemy/Provider";
import { Resource } from "alchemy/Resource";
import { createInternalTags, createTagsList, diffTags, hasAlchemyTags } from "alchemy/Tags";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Redacted from "effect/Redacted";
import * as Schedule from "effect/Schedule";
import * as Stream from "effect/Stream";
import { AWSEnvironment } from "../Environment.ts";
import type { Providers } from "../Providers.ts";
/**
* The kind of value the parameter stores.
*
* - `String` — plain text value (the default).
* - `StringList` — comma-separated list of values.
* - `SecureString` — value encrypted at rest with a KMS key.
*/
export type ParameterType = "String" | "StringList" | "SecureString";
/**
* The parameter tier. `Standard` parameters are free (up to 10,000 per
* account, 4 KB values). `Advanced` parameters cost money but allow larger
* values (8 KB), higher counts, and parameter policies. `Intelligent-Tiering`
* lets Systems Manager pick the tier per request.
*/
export type ParameterTier = "Standard" | "Advanced" | "Intelligent-Tiering";
export interface ParameterProps {
/**
* The fully qualified name of the parameter (may be a hierarchical path
* such as `/my-app/prod/db-url`). If omitted, a deterministic physical
* name is generated from the app, stage, and logical ID.
*/
name?: string;
/**
* The type of the parameter.
* @default "String"
*/
type?: ParameterType;
/**
* The parameter value. Accepts a plain string or a `Redacted` string —
* use `Redacted.make(...)` for `SecureString` values so they never leak
* into logs.
*/
value: string | Redacted.Redacted<string>;
/**
* Description of the parameter.
*/
description?: string;
/**
* The parameter tier. Note: downgrading an `Advanced` parameter back to
* `Standard` is not supported by the API and triggers a replacement.
* @default "Standard"
*/
tier?: ParameterTier;
/**
* The KMS key ID, alias (e.g. `alias/my-key`), or ARN used to encrypt a
* `SecureString` parameter. Only valid when `type` is `SecureString`.
* @default "alias/aws/ssm" (the AWS-managed key)
*/
keyId?: string;
/**
* A regular expression the parameter value must match, e.g. `^\d+
.repos/alchemy-effect/packages/aws/src/SSM/Parameter.ts at main · sailfork/t3code-github · Sailfork
.
*/
allowedPattern?: string;
/**
* The data type for a `String` parameter. Use `aws:ec2:image` to have
* Systems Manager validate the value is a valid AMI ID.
* @default "text"
*/
dataType?: "text" | "aws:ec2:image" | "aws:ssm:integration";
/**
* Tags to apply to the parameter. Merged with internal Alchemy tags.
*/
tags?: Record<string, string>;
}
export interface Parameter extends Resource<
"AWS.SSM.Parameter",
ParameterProps,
{
parameterName: string;
parameterArn: string;
type: ParameterType;
version: number;
/**
* The ARN of the KMS key that encrypts this parameter. Defined only for
* `SecureString` parameters (resolved from `keyId`, defaulting to the
* AWS-managed `alias/aws/ssm` key). Bindings use it to grant
* `kms:Decrypt` for `WithDecryption` reads.
*/
keyArn: string | undefined;
/**
* The declared description, tier, allowed pattern and data type, and
* the tags, as observed. Lets `alchemy drift` detect out-of-band
* changes.
*/
configuration?: {
description?: string;
tier?: string;
allowedPattern?: string;
dataType?: string;
tags: Record<string, string>;
};
},
never,
Providers
> {}
/**
* An AWS Systems Manager (SSM) Parameter Store parameter.
*
* `Parameter` owns the lifecycle of a `String`, `StringList`, or
* `SecureString` parameter. A parameter name is auto-generated from the app,
* stage, and logical ID unless you provide one explicitly. Standard-tier
* parameters are free, making them ideal for configuration values, feature
* flags, and small secrets.
* ### Creating Parameters
* **Example:** String Parameter
* ```typescript
* import * as SSM from "@alchemy.run/aws/SSM";
*
* const config = yield* SSM.Parameter("DatabaseUrl", {
* value: "postgres://db.example.com:5432/app",
* });
* ```
*
* **Example:** StringList Parameter
* ```typescript
* const subnets = yield* SSM.Parameter("AllowedOrigins", {
* type: "StringList",
* value: "https://a.example.com,https://b.example.com",
* });
* ```
*
* **Example:** Parameter with a Hierarchical Name
* ```typescript
* const param = yield* SSM.Parameter("DbUrl", {
* name: "/my-app/prod/db-url",
* value: "postgres://db.example.com:5432/app",
* });
* ```
*
* ### SecureString Parameters
* **Example:** Encrypted with the AWS-managed key
* ```typescript
* import * as Redacted from "effect/Redacted";
*
* const apiKey = yield* SSM.Parameter("ApiKey", {
* type: "SecureString",
* value: Redacted.make("super-secret-value"),
* });
* ```
*
* **Example:** Encrypted with a customer-managed KMS key
* ```typescript
* const key = yield* KMS.Key("SecretsKey");
* const apiKey = yield* SSM.Parameter("ApiKey", {
* type: "SecureString",
* value: Redacted.make("super-secret-value"),
* keyId: key.keyId,
* });
* ```
*
* ### Validation
* **Example:** Constrain values with an allowed pattern
* ```typescript
* const port = yield* SSM.Parameter("Port", {
* value: "5432",
* allowedPattern: "^\\d+$",
* });
* ```
*
* ### Reading Parameters at Runtime
* Bind read operations in the init phase and use them in runtime handlers.
*
* **Example:** Read a parameter from a handler
* ```typescript
* // init
* const getParameter = yield* SSM.GetParameter(config);
*
* return {
* fetch: Effect.gen(function* () {
* // runtime
* const result = yield* getParameter({ WithDecryption: true });
* return HttpServerResponse.text(String(result.Parameter?.Value));
* }),
* };
* ```
*
* @resource
*/
export const Parameter = Resource<Parameter>("AWS.SSM.Parameter");
/** Normalize a plain or redacted parameter value to its plain string. */
const toPlainValue = (value: string | Redacted.Redacted<string> | undefined): string | undefined =>
value === undefined ? undefined : typeof value === "string" ? value : Redacted.value(value);
const toTagRecord = (
tags: ReadonlyArray<{ Key?: string; Value?: string }> | undefined,
): Record<string, string> =>
Object.fromEntries(
(tags ?? [])
.filter(
(tag): tag is { Key: string; Value: string } =>
typeof tag.Key === "string" && typeof tag.Value === "string",
)
.map((tag) => [tag.Key, tag.Value]),
);
const parameterArnOf = (region: string, accountId: string, name: string) =>
`arn:aws:ssm:${region}:${accountId}:parameter${name.startsWith("/") ? "" : "/"}${name}`;
export const ParameterProvider = () =>
Provider.effect(
Parameter,
Effect.gen(function* () {
const createName = Effect.fn(function* (id: string, props: Pick<ParameterProps, "name">) {
if (props.name) return props.name;
const generated = yield* createPhysicalName({ id, maxLength: 128 });
// SSM rejects parameter names prefixed with "aws" or "ssm"
// (case-insensitive) with a ValidationException. Stack names like
// "SSMBindings" would otherwise produce invalid physical names, so
// deterministically prefix those.
return /^(aws|ssm)/i.test(generated) ? `p-${generated}` : generated;
});
// DescribeParameters is the only API that surfaces tier, description,
// allowedPattern, and the KMS key id. It is eventually consistent, so
// treat an absent result as "no metadata yet" rather than "missing".
const describeByName = Effect.fn(function* (name: string) {
return yield* ssm.describeParameters
.pages({
ParameterFilters: [{ Key: "Name", Option: "Equals", Values: [name] }],
})
.pipe(
Stream.map((page) => page.Parameters ?? []),
Stream.flattenIterable,
Stream.runHead,
Effect.map(Option.getOrUndefined),
);
});
// Resolve a key id/alias/ARN to the key ARN for the `keyArn` attribute.
// The AWS-managed `alias/aws/ssm` key is created lazily on first use,
// so tolerate NotFound as "not resolvable yet".
const resolveKeyArn = Effect.fn(function* (keyId: string | undefined) {
return yield* kms.describeKey({ KeyId: keyId ?? "alias/aws/ssm" }).pipe(
Effect.map((r) => r.KeyMetadata?.Arn),
Effect.catchTag("NotFoundException", () => Effect.undefined),
);
});
const fetchObservedTags = Effect.fn(function* (name: string) {
return yield* ssm.listTagsForResource({ ResourceType: "Parameter", ResourceId: name }).pipe(
Effect.map((r) => toTagRecord(r.TagList)),
// A just-created (or just-deleted) parameter can transiently
// surface InvalidResourceId; treat as "no tags observed".
Effect.catchTag("InvalidResourceId", () => Effect.succeed({} as Record<string, string>)),
);
});
return Parameter.Provider.of({
stables: ["parameterName", "parameterArn"],
list: () =>
Effect.gen(function* () {
const { accountId, region } = yield* AWSEnvironment.current;
const pages = yield* ssm.describeParameters.pages({}).pipe(Stream.runCollect);
const metas = Array.from(pages).flatMap((page) => page.Parameters ?? []);
return yield* Effect.forEach(
metas.filter((m): m is typeof m & { Name: string } => m.Name != null),
(m) =>
Effect.gen(function* () {
const type = (m.Type ?? "String") as ParameterType;
const keyArn =
type === "SecureString"
? yield* resolveKeyArn(m.KeyId).pipe(Effect.orElseSucceed(() => undefined))
: undefined;
return {
parameterName: m.Name,
parameterArn: m.ARN ?? parameterArnOf(region, accountId, m.Name),
type,
version: m.Version ?? 1,
keyArn,
};
}),
{ concurrency: 5 },
);
}),
read: Effect.fn(function* ({ id, olds, output }) {
const { accountId, region } = yield* AWSEnvironment.current;
const name = output?.parameterName ?? (yield* createName(id, olds ?? {}));
const found = yield* ssm.getParameter({ Name: name }).pipe(
Effect.map((r) => r.Parameter),
Effect.catchTag("ParameterNotFound", () => Effect.undefined),
);
if (!found) return undefined;
const type = (found.Type ?? "String") as ParameterType;
const meta = yield* describeByName(name).pipe(Effect.orElseSucceed(() => undefined));
const keyArn =
type === "SecureString"
? yield* resolveKeyArn(meta?.KeyId).pipe(Effect.orElseSucceed(() => undefined))
: undefined;
const tags = yield* fetchObservedTags(name).pipe(
Effect.orElseSucceed(() => ({}) as Record<string, string>),
);
// Metadata reconcile only writes when declared is only observed
// when declared.
const attrs = {
parameterName: name,
parameterArn: found.ARN ?? parameterArnOf(region, accountId, name),
type,
version: found.Version ?? 1,
keyArn,
configuration: {
description: olds?.description === undefined ? undefined : meta?.Description,
tier: olds?.tier === undefined ? undefined : meta?.Tier,
allowedPattern: olds?.allowedPattern === undefined ? undefined : meta?.AllowedPattern,
dataType: olds?.dataType === undefined ? undefined : (meta?.DataType ?? "text"),
tags,
},
};
return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
}),
diff: Effect.fn(function* ({ id, news, olds }) {
if (!isResolved(news)) return undefined;
const oldName = yield* createName(id, olds ?? {});
const newName = yield* createName(id, news ?? {});
if (oldName !== newName) {
return { action: "replace" } as const;
}
// The API cannot downgrade an Advanced parameter back to Standard —
// the only way to converge is delete + recreate.
const oldTier = olds?.tier ?? "Standard";
const newTier = news?.tier ?? "Standard";
if (oldTier === "Advanced" && newTier === "Standard") {
return { action: "replace" } as const;
}
// Type changes (String <-> SecureString etc.) are mutable via
// PutParameter Overwrite=true, so fall through to default update.
}),
reconcile: Effect.fn(function* ({ id, news, output, session }) {
const { accountId, region } = yield* AWSEnvironment.current;
const name = output?.parameterName ?? (yield* createName(id, news));
const parameterArn = parameterArnOf(region, accountId, name);
const desiredType = news.type ?? "String";
const desiredValue = toPlainValue(news.value)!;
const internalTags = yield* createInternalTags(id);
const desiredTags = { ...news.tags, ...internalTags };
// 1. OBSERVE — cloud state is authoritative. `output` is only a
// cache of the physical name; if the parameter was deleted
// out-of-band we fall through to create.
const observed = yield* ssm.getParameter({ Name: name, WithDecryption: true }).pipe(
Effect.map((r) => r.Parameter),
Effect.catchTag("ParameterNotFound", () => Effect.undefined),
);
let version: number | undefined;
if (observed === undefined) {
// 2. ENSURE — create with tags in one call. PutParameter rejects
// Tags together with Overwrite, so if a concurrent reconciler
// won the race we fall back to an overwrite put (the tag sync
// below converges tags).
version = yield* ssm
.putParameter({
Name: name,
Value: news.value,
Type: desiredType,
Description: news.description,
KeyId: news.keyId,
AllowedPattern: news.allowedPattern,
Tier: news.tier,
DataType: news.dataType,
Tags: createTagsList(desiredTags),
})
.pipe(
Effect.map((r) => r.Version),
Effect.catchTag("ParameterAlreadyExists", () =>
ssm
.putParameter({
Name: name,
Value: news.value,
Type: desiredType,
Description: news.description,
KeyId: news.keyId,
AllowedPattern: news.allowedPattern,
Tier: news.tier,
DataType: news.dataType,
Overwrite: true,
})
.pipe(Effect.map((r) => r.Version)),
),
);
} else {
// 3. SYNC — diff observed cloud state against desired and only
// call PutParameter when something actually drifted.
// DescribeParameters carries the metadata GetParameter omits
// (tier, description, allowedPattern, KMS key id); it is
// eventually consistent so an absent record just means "can't
// prove a no-op" and we overwrite.
const meta = yield* describeByName(name).pipe(Effect.orElseSucceed(() => undefined));
const drift =
toPlainValue(observed.Value) !== desiredValue ||
(observed.Type ?? "String") !== desiredType ||
(news.description !== undefined && meta?.Description !== news.description) ||
(news.allowedPattern !== undefined && meta?.AllowedPattern !== news.allowedPattern) ||
(news.tier !== undefined && meta?.Tier !== news.tier) ||
(news.dataType !== undefined && (meta?.DataType ?? "text") !== news.dataType) ||
(desiredType === "SecureString" &&
news.keyId !== undefined &&
meta?.KeyId !== news.keyId);
if (drift) {
version = yield* ssm
.putParameter({
Name: name,
Value: news.value,
Type: desiredType,
Description: news.description,
KeyId: news.keyId,
AllowedPattern: news.allowedPattern,
Tier: news.tier,
DataType: news.dataType,
Overwrite: true,
})
.pipe(Effect.map((r) => r.Version));
} else {
version = observed.Version;
}
}
// 3b. SYNC TAGS — diff against OBSERVED cloud tags (never olds or
// output) so adoption converges. Internal Alchemy tags always
// win over user tags.
const observedTags = yield* fetchObservedTags(name);
const { upsert, removed } = diffTags(observedTags, desiredTags);
if (upsert.length > 0) {
yield* ssm
.addTagsToResource({
ResourceType: "Parameter",
ResourceId: name,
Tags: upsert,
})
.pipe(
Effect.retry({
while: (e) => e._tag === "TooManyUpdates" || e._tag === "InvalidResourceId",
schedule: Schedule.max([Schedule.fixed(1000), Schedule.recurs(5)]),
}),
);
}
if (removed.length > 0) {
yield* ssm
.removeTagsFromResource({
ResourceType: "Parameter",
ResourceId: name,
TagKeys: removed,
})
.pipe(
Effect.retry({
while: (e) => e._tag === "TooManyUpdates",
schedule: Schedule.max([Schedule.fixed(1000), Schedule.recurs(5)]),
}),
);
}
// 4. RETURN — resolve the encryption key ARN after the put so a
// first SecureString write has already materialized the
// AWS-managed alias/aws/ssm key.
const keyArn =
desiredType === "SecureString" ? yield* resolveKeyArn(news.keyId) : undefined;
yield* session.note(parameterArn);
return {
parameterName: name,
parameterArn,
type: desiredType,
version: version ?? 1,
keyArn,
// Either already observed equal, or just written by the put
// above (DescribeParameters lags writes, so it is not re-read).
configuration: {
description: news.description,
tier: news.tier,
allowedPattern: news.allowedPattern,
dataType: news.dataType,
tags: desiredTags,
},
};
}),
delete: Effect.fn(function* ({ output }) {
yield* ssm
.deleteParameter({ Name: output.parameterName })
.pipe(Effect.catchTag("ParameterNotFound", () => Effect.void));
}),
});
}),
);
.repos/alchemy-effect/packages/aws/src/SSM/Parameter.ts at main · sailfork/t3code-github · Sailfork
.\n */\n allowedPattern?: string;\n /**\n * The data type for a `String` parameter. Use `aws:ec2:image` to have\n * Systems Manager validate the value is a valid AMI ID.\n * @default \"text\"\n */\n dataType?: \"text\" | \"aws:ec2:image\" | \"aws:ssm:integration\";\n /**\n * Tags to apply to the parameter. Merged with internal Alchemy tags.\n */\n tags?: Record\u003cstring, string>;\n}\n\nexport interface Parameter extends Resource\u003c\n \"AWS.SSM.Parameter\",\n ParameterProps,\n {\n parameterName: string;\n parameterArn: string;\n type: ParameterType;\n version: number;\n /**\n * The ARN of the KMS key that encrypts this parameter. Defined only for\n * `SecureString` parameters (resolved from `keyId`, defaulting to the\n * AWS-managed `alias/aws/ssm` key). Bindings use it to grant\n * `kms:Decrypt` for `WithDecryption` reads.\n */\n keyArn: string | undefined;\n /**\n * The declared description, tier, allowed pattern and data type, and\n * the tags, as observed. Lets `alchemy drift` detect out-of-band\n * changes.\n */\n configuration?: {\n description?: string;\n tier?: string;\n allowedPattern?: string;\n dataType?: string;\n tags: Record\u003cstring, string>;\n };\n },\n never,\n Providers\n> {}\n\n/**\n * An AWS Systems Manager (SSM) Parameter Store parameter.\n *\n * `Parameter` owns the lifecycle of a `String`, `StringList`, or\n * `SecureString` parameter. A parameter name is auto-generated from the app,\n * stage, and logical ID unless you provide one explicitly. Standard-tier\n * parameters are free, making them ideal for configuration values, feature\n * flags, and small secrets.\n * ### Creating Parameters\n * **Example:** String Parameter\n * ```typescript\n * import * as SSM from \"@alchemy.run/aws/SSM\";\n *\n * const config = yield* SSM.Parameter(\"DatabaseUrl\", {\n * value: \"postgres://db.example.com:5432/app\",\n * });\n * ```\n *\n * **Example:** StringList Parameter\n * ```typescript\n * const subnets = yield* SSM.Parameter(\"AllowedOrigins\", {\n * type: \"StringList\",\n * value: \"https://a.example.com,https://b.example.com\",\n * });\n * ```\n *\n * **Example:** Parameter with a Hierarchical Name\n * ```typescript\n * const param = yield* SSM.Parameter(\"DbUrl\", {\n * name: \"/my-app/prod/db-url\",\n * value: \"postgres://db.example.com:5432/app\",\n * });\n * ```\n *\n * ### SecureString Parameters\n * **Example:** Encrypted with the AWS-managed key\n * ```typescript\n * import * as Redacted from \"effect/Redacted\";\n *\n * const apiKey = yield* SSM.Parameter(\"ApiKey\", {\n * type: \"SecureString\",\n * value: Redacted.make(\"super-secret-value\"),\n * });\n * ```\n *\n * **Example:** Encrypted with a customer-managed KMS key\n * ```typescript\n * const key = yield* KMS.Key(\"SecretsKey\");\n * const apiKey = yield* SSM.Parameter(\"ApiKey\", {\n * type: \"SecureString\",\n * value: Redacted.make(\"super-secret-value\"),\n * keyId: key.keyId,\n * });\n * ```\n *\n * ### Validation\n * **Example:** Constrain values with an allowed pattern\n * ```typescript\n * const port = yield* SSM.Parameter(\"Port\", {\n * value: \"5432\",\n * allowedPattern: \"^\\\\d+$\",\n * });\n * ```\n *\n * ### Reading Parameters at Runtime\n * Bind read operations in the init phase and use them in runtime handlers.\n *\n * **Example:** Read a parameter from a handler\n * ```typescript\n * // init\n * const getParameter = yield* SSM.GetParameter(config);\n *\n * return {\n * fetch: Effect.gen(function* () {\n * // runtime\n * const result = yield* getParameter({ WithDecryption: true });\n * return HttpServerResponse.text(String(result.Parameter?.Value));\n * }),\n * };\n * ```\n *\n * @resource\n */\nexport const Parameter = Resource\u003cParameter>(\"AWS.SSM.Parameter\");\n\n/** Normalize a plain or redacted parameter value to its plain string. */\nconst toPlainValue = (value: string | Redacted.Redacted\u003cstring> | undefined): string | undefined =>\n value === undefined ? undefined : typeof value === \"string\" ? value : Redacted.value(value);\n\nconst toTagRecord = (\n tags: ReadonlyArray\u003c{ Key?: string; Value?: string }> | undefined,\n): Record\u003cstring, string> =>\n Object.fromEntries(\n (tags ?? [])\n .filter(\n (tag): tag is { Key: string; Value: string } =>\n typeof tag.Key === \"string\" && typeof tag.Value === \"string\",\n )\n .map((tag) => [tag.Key, tag.Value]),\n );\n\nconst parameterArnOf = (region: string, accountId: string, name: string) =>\n `arn:aws:ssm:${region}:${accountId}:parameter${name.startsWith(\"/\") ? \"\" : \"/\"}${name}`;\n\nexport const ParameterProvider = () =>\n Provider.effect(\n Parameter,\n Effect.gen(function* () {\n const createName = Effect.fn(function* (id: string, props: Pick\u003cParameterProps, \"name\">) {\n if (props.name) return props.name;\n const generated = yield* createPhysicalName({ id, maxLength: 128 });\n // SSM rejects parameter names prefixed with \"aws\" or \"ssm\"\n // (case-insensitive) with a ValidationException. Stack names like\n // \"SSMBindings\" would otherwise produce invalid physical names, so\n // deterministically prefix those.\n return /^(aws|ssm)/i.test(generated) ? `p-${generated}` : generated;\n });\n\n // DescribeParameters is the only API that surfaces tier, description,\n // allowedPattern, and the KMS key id. It is eventually consistent, so\n // treat an absent result as \"no metadata yet\" rather than \"missing\".\n const describeByName = Effect.fn(function* (name: string) {\n return yield* ssm.describeParameters\n .pages({\n ParameterFilters: [{ Key: \"Name\", Option: \"Equals\", Values: [name] }],\n })\n .pipe(\n Stream.map((page) => page.Parameters ?? []),\n Stream.flattenIterable,\n Stream.runHead,\n Effect.map(Option.getOrUndefined),\n );\n });\n\n // Resolve a key id/alias/ARN to the key ARN for the `keyArn` attribute.\n // The AWS-managed `alias/aws/ssm` key is created lazily on first use,\n // so tolerate NotFound as \"not resolvable yet\".\n const resolveKeyArn = Effect.fn(function* (keyId: string | undefined) {\n return yield* kms.describeKey({ KeyId: keyId ?? \"alias/aws/ssm\" }).pipe(\n Effect.map((r) => r.KeyMetadata?.Arn),\n Effect.catchTag(\"NotFoundException\", () => Effect.undefined),\n );\n });\n\n const fetchObservedTags = Effect.fn(function* (name: string) {\n return yield* ssm.listTagsForResource({ ResourceType: \"Parameter\", ResourceId: name }).pipe(\n Effect.map((r) => toTagRecord(r.TagList)),\n // A just-created (or just-deleted) parameter can transiently\n // surface InvalidResourceId; treat as \"no tags observed\".\n Effect.catchTag(\"InvalidResourceId\", () => Effect.succeed({} as Record\u003cstring, string>)),\n );\n });\n\n return Parameter.Provider.of({\n stables: [\"parameterName\", \"parameterArn\"],\n\n list: () =>\n Effect.gen(function* () {\n const { accountId, region } = yield* AWSEnvironment.current;\n const pages = yield* ssm.describeParameters.pages({}).pipe(Stream.runCollect);\n const metas = Array.from(pages).flatMap((page) => page.Parameters ?? []);\n return yield* Effect.forEach(\n metas.filter((m): m is typeof m & { Name: string } => m.Name != null),\n (m) =>\n Effect.gen(function* () {\n const type = (m.Type ?? \"String\") as ParameterType;\n const keyArn =\n type === \"SecureString\"\n ? yield* resolveKeyArn(m.KeyId).pipe(Effect.orElseSucceed(() => undefined))\n : undefined;\n return {\n parameterName: m.Name,\n parameterArn: m.ARN ?? parameterArnOf(region, accountId, m.Name),\n type,\n version: m.Version ?? 1,\n keyArn,\n };\n }),\n { concurrency: 5 },\n );\n }),\n\n read: Effect.fn(function* ({ id, olds, output }) {\n const { accountId, region } = yield* AWSEnvironment.current;\n const name = output?.parameterName ?? (yield* createName(id, olds ?? {}));\n const found = yield* ssm.getParameter({ Name: name }).pipe(\n Effect.map((r) => r.Parameter),\n Effect.catchTag(\"ParameterNotFound\", () => Effect.undefined),\n );\n if (!found) return undefined;\n const type = (found.Type ?? \"String\") as ParameterType;\n const meta = yield* describeByName(name).pipe(Effect.orElseSucceed(() => undefined));\n const keyArn =\n type === \"SecureString\"\n ? yield* resolveKeyArn(meta?.KeyId).pipe(Effect.orElseSucceed(() => undefined))\n : undefined;\n const tags = yield* fetchObservedTags(name).pipe(\n Effect.orElseSucceed(() => ({}) as Record\u003cstring, string>),\n );\n // Metadata reconcile only writes when declared is only observed\n // when declared.\n const attrs = {\n parameterName: name,\n parameterArn: found.ARN ?? parameterArnOf(region, accountId, name),\n type,\n version: found.Version ?? 1,\n keyArn,\n configuration: {\n description: olds?.description === undefined ? undefined : meta?.Description,\n tier: olds?.tier === undefined ? undefined : meta?.Tier,\n allowedPattern: olds?.allowedPattern === undefined ? undefined : meta?.AllowedPattern,\n dataType: olds?.dataType === undefined ? undefined : (meta?.DataType ?? \"text\"),\n tags,\n },\n };\n return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);\n }),\n\n diff: Effect.fn(function* ({ id, news, olds }) {\n if (!isResolved(news)) return undefined;\n const oldName = yield* createName(id, olds ?? {});\n const newName = yield* createName(id, news ?? {});\n if (oldName !== newName) {\n return { action: \"replace\" } as const;\n }\n // The API cannot downgrade an Advanced parameter back to Standard —\n // the only way to converge is delete + recreate.\n const oldTier = olds?.tier ?? \"Standard\";\n const newTier = news?.tier ?? \"Standard\";\n if (oldTier === \"Advanced\" && newTier === \"Standard\") {\n return { action: \"replace\" } as const;\n }\n // Type changes (String \u003c-> SecureString etc.) are mutable via\n // PutParameter Overwrite=true, so fall through to default update.\n }),\n\n reconcile: Effect.fn(function* ({ id, news, output, session }) {\n const { accountId, region } = yield* AWSEnvironment.current;\n const name = output?.parameterName ?? (yield* createName(id, news));\n const parameterArn = parameterArnOf(region, accountId, name);\n const desiredType = news.type ?? \"String\";\n const desiredValue = toPlainValue(news.value)!;\n const internalTags = yield* createInternalTags(id);\n const desiredTags = { ...news.tags, ...internalTags };\n\n // 1. OBSERVE — cloud state is authoritative. `output` is only a\n // cache of the physical name; if the parameter was deleted\n // out-of-band we fall through to create.\n const observed = yield* ssm.getParameter({ Name: name, WithDecryption: true }).pipe(\n Effect.map((r) => r.Parameter),\n Effect.catchTag(\"ParameterNotFound\", () => Effect.undefined),\n );\n\n let version: number | undefined;\n\n if (observed === undefined) {\n // 2. ENSURE — create with tags in one call. PutParameter rejects\n // Tags together with Overwrite, so if a concurrent reconciler\n // won the race we fall back to an overwrite put (the tag sync\n // below converges tags).\n version = yield* ssm\n .putParameter({\n Name: name,\n Value: news.value,\n Type: desiredType,\n Description: news.description,\n KeyId: news.keyId,\n AllowedPattern: news.allowedPattern,\n Tier: news.tier,\n DataType: news.dataType,\n Tags: createTagsList(desiredTags),\n })\n .pipe(\n Effect.map((r) => r.Version),\n Effect.catchTag(\"ParameterAlreadyExists\", () =>\n ssm\n .putParameter({\n Name: name,\n Value: news.value,\n Type: desiredType,\n Description: news.description,\n KeyId: news.keyId,\n AllowedPattern: news.allowedPattern,\n Tier: news.tier,\n DataType: news.dataType,\n Overwrite: true,\n })\n .pipe(Effect.map((r) => r.Version)),\n ),\n );\n } else {\n // 3. SYNC — diff observed cloud state against desired and only\n // call PutParameter when something actually drifted.\n // DescribeParameters carries the metadata GetParameter omits\n // (tier, description, allowedPattern, KMS key id); it is\n // eventually consistent so an absent record just means \"can't\n // prove a no-op\" and we overwrite.\n const meta = yield* describeByName(name).pipe(Effect.orElseSucceed(() => undefined));\n const drift =\n toPlainValue(observed.Value) !== desiredValue ||\n (observed.Type ?? \"String\") !== desiredType ||\n (news.description !== undefined && meta?.Description !== news.description) ||\n (news.allowedPattern !== undefined && meta?.AllowedPattern !== news.allowedPattern) ||\n (news.tier !== undefined && meta?.Tier !== news.tier) ||\n (news.dataType !== undefined && (meta?.DataType ?? \"text\") !== news.dataType) ||\n (desiredType === \"SecureString\" &&\n news.keyId !== undefined &&\n meta?.KeyId !== news.keyId);\n if (drift) {\n version = yield* ssm\n .putParameter({\n Name: name,\n Value: news.value,\n Type: desiredType,\n Description: news.description,\n KeyId: news.keyId,\n AllowedPattern: news.allowedPattern,\n Tier: news.tier,\n DataType: news.dataType,\n Overwrite: true,\n })\n .pipe(Effect.map((r) => r.Version));\n } else {\n version = observed.Version;\n }\n }\n\n // 3b. SYNC TAGS — diff against OBSERVED cloud tags (never olds or\n // output) so adoption converges. Internal Alchemy tags always\n // win over user tags.\n const observedTags = yield* fetchObservedTags(name);\n const { upsert, removed } = diffTags(observedTags, desiredTags);\n if (upsert.length > 0) {\n yield* ssm\n .addTagsToResource({\n ResourceType: \"Parameter\",\n ResourceId: name,\n Tags: upsert,\n })\n .pipe(\n Effect.retry({\n while: (e) => e._tag === \"TooManyUpdates\" || e._tag === \"InvalidResourceId\",\n schedule: Schedule.max([Schedule.fixed(1000), Schedule.recurs(5)]),\n }),\n );\n }\n if (removed.length > 0) {\n yield* ssm\n .removeTagsFromResource({\n ResourceType: \"Parameter\",\n ResourceId: name,\n TagKeys: removed,\n })\n .pipe(\n Effect.retry({\n while: (e) => e._tag === \"TooManyUpdates\",\n schedule: Schedule.max([Schedule.fixed(1000), Schedule.recurs(5)]),\n }),\n );\n }\n\n // 4. RETURN — resolve the encryption key ARN after the put so a\n // first SecureString write has already materialized the\n // AWS-managed alias/aws/ssm key.\n const keyArn =\n desiredType === \"SecureString\" ? yield* resolveKeyArn(news.keyId) : undefined;\n\n yield* session.note(parameterArn);\n return {\n parameterName: name,\n parameterArn,\n type: desiredType,\n version: version ?? 1,\n keyArn,\n // Either already observed equal, or just written by the put\n // above (DescribeParameters lags writes, so it is not re-read).\n configuration: {\n description: news.description,\n tier: news.tier,\n allowedPattern: news.allowedPattern,\n dataType: news.dataType,\n tags: desiredTags,\n },\n };\n }),\n\n delete: Effect.fn(function* ({ output }) {\n yield* ssm\n .deleteParameter({ Name: output.parameterName })\n .pipe(Effect.catchTag(\"ParameterNotFound\", () => Effect.void));\n }),\n });\n }),\n );\n","preview":null,"history":null,"version":"5e0820ca539e46b4bdf204bbfc76194bcfbbe344"},"/_session?shell=1":null}