@geekmidas/constructs 10.0.0-alpha.184 → 10.0.0-alpha.186

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.
@@ -2,7 +2,7 @@ import { n as StandardSchemaV1 } from "./index-DdRjYhiJ.mjs";
2
2
  import { t as Construct } from "./Construct-BMk_CRSD.mjs";
3
3
  import { r as Consumable, u as ServicesOf } from "./construct-interface-Nw5Dt9AC.mjs";
4
4
  import { DERIVED_PREFIX as DERIVED_PREFIX$1 } from "@geekmidas/manifest";
5
- import { StorageClient } from "@geekmidas/storage";
5
+ import { ObjectMetadata, StorageClient } from "@geekmidas/storage";
6
6
  import { Service, ServiceRecord } from "@geekmidas/services";
7
7
  import { Logger } from "@geekmidas/logger";
8
8
  import { InferStandardSchema } from "@geekmidas/schema";
@@ -88,12 +88,26 @@ interface ProcessorResult {
88
88
  */
89
89
  cache?: ProcessorCache;
90
90
  }
91
- /** The object a request addresses, read from the bucket on first use. */
91
+ /**
92
+ * The object a request addresses, read from the bucket on first use.
93
+ *
94
+ * Its body is one GET, made by the first `bytes()` or `stream()`; what is
95
+ * known about it is one HEAD, made by the first `size()` or `metadata()`.
96
+ * Either throws `ProcessorSourceMissing` when the object is not there, which
97
+ * answers the request with a 404.
98
+ */
92
99
  interface SourceObject {
93
100
  readonly key: string;
101
+ /** Its size in bytes, from a HEAD: the body is not downloaded. */
102
+ size(): Promise<number>;
103
+ /** Everything a HEAD answers, without downloading the body. */
104
+ metadata(): Promise<ObjectMetadata>;
94
105
  bytes(): Promise<Uint8Array>;
95
106
  stream(): Promise<ReadableStream<Uint8Array>>;
96
- /** The type it was stored with. */
107
+ /**
108
+ * The type it was stored with: from the body's response when it has
109
+ * already been read, otherwise from a HEAD.
110
+ */
97
111
  contentType(): Promise<string | undefined>;
98
112
  }
99
113
  interface ProcessorContext<TParams, TServices extends Service[], TLogger extends Logger> {
@@ -213,4 +227,4 @@ declare class ProcessorBuilder<TPattern extends string, TSchema extends Standard
213
227
  }
214
228
  //#endregion
215
229
  export { parsePattern as _, ProcessorCache as a, ProcessorParams as c, ParsedPattern as d, PatternParams as f, matchPattern as g, fillPattern as h, Processor as i, ProcessorResult as l, ProcessorPatternInvalid as m, ProcessorNativeInvalid as n, ProcessorContext as o, ProcessorParamMissing as p, DERIVED_PREFIX$1 as r, ProcessorHandler as s, ProcessorBuilder as t, SourceObject as u };
216
- //# sourceMappingURL=ProcessorBuilder-CdLwJK4k.d.mts.map
230
+ //# sourceMappingURL=ProcessorBuilder-CekwYHGD.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ProcessorBuilder-CekwYHGD.d.mts","names":[],"sources":["../src/processors/pattern.ts","../src/processors/Processor.ts","../src/processors/ProcessorBuilder.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;KAeY,kBAAkB,oBAC7B,8BAA8B,cAAc,SACzC,OAAO,sBAAsB;;KAIrB,cAAc,uBACxB,KAAK,kBAAkB;;cAIZ,gCAAgC;WAElC;WACA;EAFV,YACU,iBACA;;;UAYM;WACP;;WAEA;IACJ;IAAiB;;IACjB;IAAe;;;WAGX;;WAEA;;;iBAIM,aAAa,kBAAkB;;UAkE9B;EAChB,QAAQ;EACR;;;;;;iBAOe,aACf,QAAQ,eACR,eACE;;iBA0Ba,YACf,QAAQ,eACR,QAAQ,SAAS,kCACjB;;cAmBY,8BAA8B;WAEhC;WACA;EAFV,YACU,iBACA;;;;;KCtKC;;;;;EAIP;;;;;UAKY;EAChB,MAAM;EACN;;;;;EAKA,QAAQ;;;;;;;;;;UAWQ;WACP;;EAET,QAAQ;;EAER,YAAY,QAAQ;EACpB,SAAS,QAAQ;EACjB,UAAU,QAAQ,eAAe;;;;;EAKjC,eAAe;;UAGC,iBAChB,SACA,kBAAkB,WAClB,gBAAgB;EAEhB,QAAQ;EACR;EACA,QAAQ;EACR,QAAQ;EACR,UAAU,cAAc;;KAGb,iBACX,SACA,kBAAkB,WAClB,gBAAgB,WAEhB,SA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ger";
5
5
  import { InferStandardSchema } from "@geekmidas/schema";
6
6
  import { Service, ServiceRecord } from "@geekmidas/services";
7
7
  import { DERIVED_PREFIX } from "@geekmidas/manifest";
8
- import { StorageClient } from "@geekmidas/storage";
8
+ import { ObjectMetadata, StorageClient } from "@geekmidas/storage";
9
9
  //#region src/processors/pattern.d.ts
10
10
  /**
11
11
  * A processor's path pattern: literal segments, `:name` parameters, and a
@@ -88,12 +88,26 @@ interface ProcessorResult {
88
88
  */
89
89
  cache?: ProcessorCache;
90
90
  }
91
- /** The object a request addresses, read from the bucket on first use. */
91
+ /**
92
+ * The object a request addresses, read from the bucket on first use.
93
+ *
94
+ * Its body is one GET, made by the first `bytes()` or `stream()`; what is
95
+ * known about it is one HEAD, made by the first `size()` or `metadata()`.
96
+ * Either throws `ProcessorSourceMissing` when the object is not there, which
97
+ * answers the request with a 404.
98
+ */
92
99
  interface SourceObject {
93
100
  readonly key: string;
101
+ /** Its size in bytes, from a HEAD: the body is not downloaded. */
102
+ size(): Promise<number>;
103
+ /** Everything a HEAD answers, without downloading the body. */
104
+ metadata(): Promise<ObjectMetadata>;
94
105
  bytes(): Promise<Uint8Array>;
95
106
  stream(): Promise<ReadableStream<Uint8Array>>;
96
- /** The type it was stored with. */
107
+ /**
108
+ * The type it was stored with: from the body's response when it has
109
+ * already been read, otherwise from a HEAD.
110
+ */
97
111
  contentType(): Promise<string | undefined>;
98
112
  }
99
113
  interface ProcessorContext<TParams, TServices extends Service[], TLogger extends Logger> {
@@ -213,4 +227,4 @@ declare class ProcessorBuilder<TPattern extends string, TSchema extends Standard
213
227
  }
214
228
  //#endregion
215
229
  export { parsePattern as _, ProcessorCache as a, ProcessorParams as c, ParsedPattern as d, PatternParams as f, matchPattern as g, fillPattern as h, Processor as i, ProcessorResult as l, ProcessorPatternInvalid as m, ProcessorNativeInvalid as n, ProcessorContext as o, ProcessorParamMissing as p, DERIVED_PREFIX as r, ProcessorHandler as s, ProcessorBuilder as t, SourceObject as u };
216
- //# sourceMappingURL=ProcessorBuilder-ClD7tmEe.d.cts.map
230
+ //# sourceMappingURL=ProcessorBuilder-DLUxw6op.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ProcessorBuilder-DLUxw6op.d.cts","names":[],"sources":["../src/processors/pattern.ts","../src/processors/Processor.ts","../src/processors/ProcessorBuilder.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;KAeY,kBAAkB,oBAC7B,8BAA8B,cAAc,SACzC,OAAO,sBAAsB;;KAIrB,cAAc,uBACxB,KAAK,kBAAkB;;cAIZ,gCAAgC;WAElC;WACA;EAFV,YACU,iBACA;;;UAYM;WACP;;WAEA;IACJ;IAAiB;;IACjB;IAAe;;;WAGX;;WAEA;;;iBAIM,aAAa,kBAAkB;;UAkE9B;EAChB,QAAQ;EACR;;;;;;iBAOe,aACf,QAAQ,eACR,eACE;;iBA0Ba,YACf,QAAQ,eACR,QAAQ,SAAS,kCACjB;;cAmBY,8BAA8B;WAEhC;WACA;EAFV,YACU,iBACA;;;;;KCtKC;;;;;EAIP;;;;;UAKY;EAChB,MAAM;EACN;;;;;EAKA,QAAQ;;;;;;;;;;UAWQ;WACP;;EAET,QAAQ;;EAER,YAAY,QAAQ;EACpB,SAAS,QAAQ;EACjB,UAAU,QAAQ,eAAe;;;;;EAKjC,eAAe;;UAGC,iBAChB,SACA,kBAAkB,WAClB,gBAAgB;EAEhB,QAAQ;EACR;EACA,QAAQ;EACR,QAAQ;EACR,UAAU,cAAc;;KAGb,iBACX,SACA,kBAAkB,WAClB,gBAAgB,WAEhB,SAAS,iBAAiB,SAAS,WAAW,aAC1C,QAAQ,mBAAmB;;KAGpB,gBACX,yBACA,gBAAgB,gCACb,gBAAgB,mBACjB,oBAAoB,WACpB,cAAc;;;;;;;;;;cAWJ,UACZ,kCACA,gBAAgB,0CAChB,kBAAkB,gBAClB,gBAAgB,SAAS,gBAChB,UAAU,oBAAoB;WAY7B,QAAQ;WACR,SAAS,iBACjB,gBAAgB,UAAU,UAC1B,WACA;WAEQ;;IAER;;IAEA;;IAEA,QAAQ,gBAAgB;;IAExB,SAAS;IACT,eAAe;;IAEf;IACA,QAAQ;IACR,UAAU;IACV;IACA;IACA;;EAjCF;SAEO,YAAY,eAAe,OAAO;EAQzC,YACU,QAAQ,eACR,SAAS,iBACjB,gBAAgB,UAAU,UAC1B,WACA,UAEQ;;IAER;;IAEA;;IAEA,QAAQ,gBAAgB;;IAExB,SAAS;IACT,eAAe;;IAEf;IACA,QAAQ;IACR,UAAU;IACV;IACA;IACA;;;MAsBE,WAAW;;MAKX;MAIA;MAIA;MAIA;;;;;cC7JQ,+BAA+B;WACtB;EAArB,YAAqB;;UAUZ,sBAAsB,gBAAgB;EAC/C,QAAQ;EACR;EACA;EACA,QAAQ,gBAAgB;EACxB,SAAS;EACT,QAAQ;EACR,eAAe;EACf;EACA,UAAU;EACV;EACA;EACA;;;;;;cAOY,iBACZ,yBACA,gBAAgB,0CAChB,kBAAkB,gBAClB,gBAAgB,SAAS;mBAEI;EAA7B,YAA6B,OAAO,sBAAsB;;;;;EAM1D,OAAO,UAAU,kBAChB,QAAQ,IACN,iBAAiB,UAAU,GAAG,WAAW;;EAK5C,gBAAgB,mBAAmB,cAClC,YAAY,IACV,iBACF,UACA,aACI,cAAc,WAAW,KAC7B;;;;;;EAqBD,OAAO;;EAaP,QAAQ;;EAKR,WAAW;EAIX,OACC,IAAI,iBACH,gBAAgB,UAAU,UAC1B,WACA,WAEC,UAAU,UAAU,SAAS,WAAW"}
@@ -2,7 +2,7 @@ import { n as StandardSchemaV1 } from "./index-DdRjYhiJ.cjs";
2
2
  import { a as HasPublicFace, i as Declarable, l as ServerHalf, n as Construct } from "./construct-interface-CVoejIpo.cjs";
3
3
  import { n as Telemetry } from "./telemetry-BbLyS7ln.cjs";
4
4
  import { r as ObjectExpiry } from "./expire-C586zznE.cjs";
5
- import { f as PatternParams, i as Processor, t as ProcessorBuilder } from "./ProcessorBuilder-ClD7tmEe.cjs";
5
+ import { f as PatternParams, i as Processor, t as ProcessorBuilder } from "./ProcessorBuilder-DLUxw6op.cjs";
6
6
  import { Logger } from "@geekmidas/logger";
7
7
  import { Service } from "@geekmidas/services";
8
8
  import { ConstructName, Declaration } from "@geekmidas/manifest";
@@ -2,7 +2,7 @@ import { n as StandardSchemaV1 } from "./index-DdRjYhiJ.mjs";
2
2
  import { a as HasPublicFace, i as Declarable, l as ServerHalf, n as Construct } from "./construct-interface-Nw5Dt9AC.mjs";
3
3
  import { n as Telemetry } from "./telemetry-DWX-qKUh.mjs";
4
4
  import { r as ObjectExpiry } from "./expire-C586zznE.mjs";
5
- import { f as PatternParams, i as Processor, t as ProcessorBuilder } from "./ProcessorBuilder-CdLwJK4k.mjs";
5
+ import { f as PatternParams, i as Processor, t as ProcessorBuilder } from "./ProcessorBuilder-CekwYHGD.mjs";
6
6
  import { ConstructName, Declaration } from "@geekmidas/manifest";
7
7
  import { StorageClient } from "@geekmidas/storage";
8
8
  import { Service } from "@geekmidas/services";
@@ -1 +1 @@
1
- {"version":3,"file":"pattern-C1CEcglD.mjs","names":[],"sources":["../src/processors/Processor.ts","../src/processors/ProcessorBuilder.ts","../src/processors/pattern.ts"],"sourcesContent":["import type { Logger } from '@geekmidas/logger';\nimport type { InferStandardSchema } from '@geekmidas/schema';\nimport type { Service, ServiceRecord } from '@geekmidas/services';\nimport type { StorageClient } from '@geekmidas/storage';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { Construct, ConstructType } from '../Construct';\nimport type { ParsedPattern, PatternParams } from './pattern';\n\n/**\n * Where a processor's results are kept, under its file server's bucket.\n *\n * Written through on every result marked `immutable` and read before the\n * handler runs, so a derivative is made once. Exported so the bucket's expiry\n * can name it.\n */\nexport { DERIVED_PREFIX } from '@geekmidas/manifest';\n\n/** How long a response may be kept, by a browser and by the edge. */\nexport type ProcessorCache =\n\t/** Never changes for these parameters and this key: kept for a year. */\n\t| 'immutable'\n\t/** Kept this many seconds. */\n\t| { maxAge: number }\n\t/** Not kept. */\n\t| 'none';\n\n/** What a processor handler returns. */\nexport interface ProcessorResult {\n\tbody: Uint8Array | string;\n\tcontentType: string;\n\t/**\n\t * `immutable` results are also kept in the bucket, so the next request\n\t * for them never runs the handler. Defaults to an hour, kept nowhere.\n\t */\n\tcache?: ProcessorCache;\n}\n\n/** The object a request addresses, read from the bucket on first use. */\nexport interface SourceObject {\n\treadonly key: string;\n\tbytes(): Promise<Uint8Array>;\n\tstream(): Promise<ReadableStream<Uint8Array>>;\n\t/** The type it was stored with. */\n\tcontentType(): Promise<string | undefined>;\n}\n\nexport interface ProcessorContext<\n\tTParams,\n\tTServices extends Service[],\n\tTLogger extends Logger,\n> {\n\tparams: TParams;\n\tkey: string;\n\tobject: SourceObject;\n\tlogger: TLogger;\n\tservices: ServiceRecord<TServices>;\n}\n\nexport type ProcessorHandler<\n\tTParams,\n\tTServices extends Service[],\n\tTLogger extends Logger,\n> = (\n\tcontext: ProcessorContext<TParams, TServices, TLogger>,\n) => Promise<ProcessorResult> | ProcessorResult;\n\n/** What a processor's parameters parse to: its schema's output, or the raw strings. */\nexport type ProcessorParams<\n\tTPattern extends string,\n\tTSchema extends StandardSchemaV1 | undefined,\n> = TSchema extends StandardSchemaV1\n\t? InferStandardSchema<TSchema>\n\t: PatternParams<TPattern>;\n\n/**\n * A processor — a handler behind one path pattern of a file server, which\n * makes a derivative of an open object on read: a thumbnail, a page of a PDF.\n *\n * Built from the file server (`assets.process('/i/:width/*')`), so it carries\n * the bucket it reads and the open paths it may serve. Its parameters' schema\n * is the allowlist: a request outside it is refused before anything runs, so\n * nobody can mint new work — or new cache entries — by varying a number.\n */\nexport class Processor<\n\tTPattern extends string = string,\n\tTSchema extends StandardSchemaV1 | undefined = undefined,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n> extends Construct<TLogger, undefined, TServices> {\n\t__IS_PROCESSOR__ = true;\n\n\tstatic isProcessor(obj: unknown): obj is Processor<string, any, any, any> {\n\t\treturn Boolean(\n\t\t\tobj &&\n\t\t\t\t(obj as { __IS_PROCESSOR__?: boolean }).__IS_PROCESSOR__ === true &&\n\t\t\t\t(obj as Construct).type === ConstructType.Processor,\n\t\t);\n\t}\n\n\tconstructor(\n\t\treadonly parsed: ParsedPattern,\n\t\treadonly handler: ProcessorHandler<\n\t\t\tProcessorParams<TPattern, TSchema>,\n\t\t\tTServices,\n\t\t\tTLogger\n\t\t>,\n\t\treadonly options: {\n\t\t\t/** The file server's surface id — the unit that runs it. */\n\t\t\tsurfaceId: string;\n\t\t\t/** The bucket it reads from and keeps derivatives in. */\n\t\t\tbucketId: string;\n\t\t\t/** How it reaches that bucket. */\n\t\t\torigin: Service<string, StorageClient>;\n\t\t\t/** Whether a key is one of the file server's open paths. */\n\t\t\tserves: (key: string) => boolean;\n\t\t\tparamsSchema?: TSchema;\n\t\t\t/** Packages with native code, installed for the target. */\n\t\t\tnative: readonly string[];\n\t\t\tlogger: TLogger;\n\t\t\tservices: TServices;\n\t\t\tconstructs: string[];\n\t\t\ttimeout?: number;\n\t\t\tmemorySize?: number;\n\t\t},\n\t) {\n\t\tsuper(\n\t\t\tConstructType.Processor,\n\t\t\toptions.logger,\n\t\t\t// The bucket is reached like any service — which is also how its URL\n\t\t\t// is found by the environment sniffer.\n\t\t\t[options.origin, ...options.services] as unknown as TServices,\n\t\t\t[],\n\t\t\tundefined,\n\t\t\toptions.timeout,\n\t\t\toptions.memorySize,\n\t\t\tundefined,\n\t\t\t// The bucket is an edge of its process, so the unit running it is\n\t\t\t// handed the bucket's address.\n\t\t\t[...new Set([options.bucketId, ...options.constructs])],\n\t\t);\n\t\tthis.owner = options.surfaceId;\n\t}\n\n\t/** The pattern it answers, as written. */\n\tget pattern(): TPattern {\n\t\treturn this.parsed.pattern as TPattern;\n\t}\n\n\t/** The literal path the edge routes to it — `/i/`. */\n\tget prefix(): string {\n\t\treturn this.parsed.prefix;\n\t}\n\n\tget native(): readonly string[] {\n\t\treturn this.options.native;\n\t}\n\n\tget surfaceId(): string {\n\t\treturn this.options.surfaceId;\n\t}\n\n\tget bucketId(): string {\n\t\treturn this.options.bucketId;\n\t}\n}\n","import type { Logger } from '@geekmidas/logger';\nimport type { Service } from '@geekmidas/services';\nimport type { StorageClient } from '@geekmidas/storage';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport {\n\ttype Consumable,\n\tidsOf,\n\ttype ServicesOf,\n\tservicesOf,\n} from '../construct-interface';\nimport {\n\tProcessor,\n\ttype ProcessorHandler,\n\ttype ProcessorParams,\n} from './Processor';\nimport type { ParsedPattern } from './pattern';\n\n/** A native package named in a way no installer could resolve. */\nexport class ProcessorNativeInvalid extends Error {\n\tconstructor(readonly packageName: string) {\n\t\tsuper(\n\t\t\t`'${packageName}' is not a package name. Name the package with native code ` +\n\t\t\t\t`as it is installed — 'sharp', '@napi-rs/canvas' — and its version ` +\n\t\t\t\t`is taken from the app's package.json.`,\n\t\t);\n\t\tthis.name = 'ProcessorNativeInvalid';\n\t}\n}\n\ninterface ProcessorBuilderState<TLogger extends Logger> {\n\tparsed: ParsedPattern;\n\tsurfaceId: string;\n\tbucketId: string;\n\torigin: Service<string, StorageClient>;\n\tserves: (key: string) => boolean;\n\tlogger: TLogger;\n\tparamsSchema?: StandardSchemaV1;\n\tnative: string[];\n\tservices: Service[];\n\tconstructs: string[];\n\ttimeout?: number;\n\tmemorySize?: number;\n}\n\n/**\n * What `fileServer.process(pattern)` returns: a processor, built up one\n * immutable step at a time and finished by `.handle()`.\n */\nexport class ProcessorBuilder<\n\tTPattern extends string,\n\tTSchema extends StandardSchemaV1 | undefined = undefined,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n> {\n\tconstructor(private readonly state: ProcessorBuilderState<TLogger>) {}\n\n\t/**\n\t * The parameters' schema — the allowlist. Every request is parsed by it\n\t * before anything runs, and one it refuses is answered 400.\n\t */\n\tparams<T extends StandardSchemaV1>(\n\t\tschema: T,\n\t): ProcessorBuilder<TPattern, T, TServices, TLogger> {\n\t\treturn new ProcessorBuilder({ ...this.state, paramsSchema: schema });\n\t}\n\n\t/** Constructs its handler reaches, as `services.<id>`. */\n\tdependsOn<const T extends readonly Consumable[]>(\n\t\tconstructs: T,\n\t): ProcessorBuilder<\n\t\tTPattern,\n\t\tTSchema,\n\t\t[...TServices, ...ServicesOf<T>],\n\t\tTLogger\n\t> {\n\t\tconst services = servicesOf(constructs) as unknown as Service[];\n\t\treturn new ProcessorBuilder({\n\t\t\t...this.state,\n\t\t\tservices: [\n\t\t\t\t...this.state.services.filter(\n\t\t\t\t\t(service) =>\n\t\t\t\t\t\t!services.some((s) => s.serviceName === service.serviceName),\n\t\t\t\t),\n\t\t\t\t...services,\n\t\t\t],\n\t\t\tconstructs: idsOf(constructs, this.state.constructs),\n\t\t});\n\t}\n\n\t/**\n\t * Packages with native code — `sharp` — installed for the target the\n\t * processor runs on rather than bundled: linux in its image, arm64 on\n\t * Lambda.\n\t */\n\tnative(packages: readonly string[]): this {\n\t\tfor (const name of packages) {\n\t\t\tif (!/^(@[a-z0-9._~-]+\\/)?[a-z0-9._~-]+$/.test(name)) {\n\t\t\t\tthrow new ProcessorNativeInvalid(name);\n\t\t\t}\n\t\t}\n\t\treturn new ProcessorBuilder({\n\t\t\t...this.state,\n\t\t\tnative: [...new Set([...this.state.native, ...packages])],\n\t\t}) as this;\n\t}\n\n\t/** Milliseconds a request may take, where the target bounds it. */\n\ttimeout(ms: number): this {\n\t\treturn new ProcessorBuilder({ ...this.state, timeout: ms }) as this;\n\t}\n\n\t/** Megabytes of memory, where the target sets it. */\n\tmemorySize(mb: number): this {\n\t\treturn new ProcessorBuilder({ ...this.state, memorySize: mb }) as this;\n\t}\n\n\thandle(\n\t\tfn: ProcessorHandler<\n\t\t\tProcessorParams<TPattern, TSchema>,\n\t\t\tTServices,\n\t\t\tTLogger\n\t\t>,\n\t): Processor<TPattern, TSchema, TServices, TLogger> {\n\t\tconst { state } = this;\n\t\treturn new Processor<TPattern, TSchema, TServices, TLogger>(\n\t\t\tstate.parsed,\n\t\t\tfn,\n\t\t\t{\n\t\t\t\tsurfaceId: state.surfaceId,\n\t\t\t\tbucketId: state.bucketId,\n\t\t\t\torigin: state.origin,\n\t\t\t\tserves: state.serves,\n\t\t\t\t...(state.paramsSchema\n\t\t\t\t\t? { paramsSchema: state.paramsSchema as TSchema }\n\t\t\t\t\t: {}),\n\t\t\t\tnative: state.native,\n\t\t\t\tlogger: state.logger,\n\t\t\t\tservices: state.services as TServices,\n\t\t\t\tconstructs: state.constructs,\n\t\t\t\t...(state.timeout !== undefined ? { timeout: state.timeout } : {}),\n\t\t\t\t...(state.memorySize !== undefined\n\t\t\t\t\t? { memorySize: state.memorySize }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t);\n\t}\n}\n","/**\n * A processor's path pattern: literal segments, `:name` parameters, and a\n * final `*` that is the object's key.\n *\n * ```\n * /i/:width/* → /i/256/avatars/7.png { width: '256' }, 'avatars/7.png'\n * /pdf/:page/:dpi/* → /pdf/1/150/doc.pdf { page: '1', dpi: '150' }, 'doc.pdf'\n * ```\n *\n * It starts with a literal segment because the edge routes on that prefix: a\n * pattern beginning with a parameter would claim every path on the file\n * server, objects included.\n */\n\n/** The parameter names a pattern declares, as a union. */\nexport type PatternParamNames<P extends string> =\n\tP extends `${string}/:${infer Name}/${infer Rest}`\n\t\t? Name | PatternParamNames<`/${Rest}`>\n\t\t: never;\n\n/** The raw parameters a pattern matches, before its schema parses them. */\nexport type PatternParams<P extends string> = {\n\t[K in PatternParamNames<P>]: string;\n};\n\n/** A pattern a processor cannot be served on. */\nexport class ProcessorPatternInvalid extends Error {\n\tconstructor(\n\t\treadonly pattern: string,\n\t\treadonly reason: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${pattern}' is not a processor pattern: ${reason}. A pattern is a ` +\n\t\t\t\t`literal first segment, then any \\`:name\\` parameters, then \\`*\\` ` +\n\t\t\t\t`for the object's key — '/i/:width/*'.`,\n\t\t);\n\t\tthis.name = 'ProcessorPatternInvalid';\n\t}\n}\n\n/** A pattern, parsed once. */\nexport interface ParsedPattern {\n\treadonly pattern: string;\n\t/** Each segment before the key: a literal, or a parameter's name. */\n\treadonly segments: readonly (\n\t\t| { kind: 'literal'; value: string }\n\t\t| { kind: 'param'; name: string }\n\t)[];\n\t/** The parameter names, in the order they appear. */\n\treadonly params: readonly string[];\n\t/** The literal path the edge routes on — `/i/`. */\n\treadonly prefix: string;\n}\n\n/** @throws {ProcessorPatternInvalid} */\nexport function parsePattern(pattern: string): ParsedPattern {\n\tif (!pattern.startsWith('/')) {\n\t\tthrow new ProcessorPatternInvalid(pattern, 'it does not start with /');\n\t}\n\tif (!pattern.endsWith('/*')) {\n\t\tthrow new ProcessorPatternInvalid(\n\t\t\tpattern,\n\t\t\t'it does not end with /* — the key',\n\t\t);\n\t}\n\n\tconst parts = pattern.slice(1, -2).split('/');\n\tconst segments: ParsedPattern['segments'][number][] = [];\n\tconst params: string[] = [];\n\tfor (const part of parts) {\n\t\tif (part === '') {\n\t\t\tthrow new ProcessorPatternInvalid(pattern, 'it has an empty segment');\n\t\t}\n\t\tif (part.includes('*')) {\n\t\t\tthrow new ProcessorPatternInvalid(\n\t\t\t\tpattern,\n\t\t\t\t'only its last segment may be *',\n\t\t\t);\n\t\t}\n\t\tif (part.startsWith(':')) {\n\t\t\tconst name = part.slice(1);\n\t\t\tif (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {\n\t\t\t\tthrow new ProcessorPatternInvalid(\n\t\t\t\t\tpattern,\n\t\t\t\t\t`'${part}' is not a parameter name`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (params.includes(name)) {\n\t\t\t\tthrow new ProcessorPatternInvalid(pattern, `'${name}' appears twice`);\n\t\t\t}\n\t\t\tparams.push(name);\n\t\t\tsegments.push({ kind: 'param', name });\n\t\t\tcontinue;\n\t\t}\n\t\tif (!/^[A-Za-z0-9._~-]+$/.test(part)) {\n\t\t\tthrow new ProcessorPatternInvalid(\n\t\t\t\tpattern,\n\t\t\t\t`'${part}' has characters a path segment would escape`,\n\t\t\t);\n\t\t}\n\t\tsegments.push({ kind: 'literal', value: part });\n\t}\n\n\tconst first = segments[0];\n\tif (!first || first.kind !== 'literal') {\n\t\tthrow new ProcessorPatternInvalid(\n\t\t\tpattern,\n\t\t\t'its first segment is a parameter, which would claim every path',\n\t\t);\n\t}\n\n\tconst literals: string[] = [];\n\tfor (const segment of segments) {\n\t\tif (segment.kind !== 'literal') break;\n\t\tliterals.push(segment.value);\n\t}\n\n\treturn { pattern, segments, params, prefix: `/${literals.join('/')}/` };\n}\n\n/** A path the pattern matched: its raw parameters and the key. */\nexport interface PatternMatch {\n\tparams: Record<string, string>;\n\tkey: string;\n}\n\n/**\n * Match a request path, decoding each parameter and each key segment. A path\n * with an empty key, or one that decodes to a `..` segment, matches nothing.\n */\nexport function matchPattern(\n\tparsed: ParsedPattern,\n\tpath: string,\n): PatternMatch | undefined {\n\tconst parts = path.replace(/^\\/+/, '').split('/');\n\tif (parts.length <= parsed.segments.length) return undefined;\n\n\tconst params: Record<string, string> = {};\n\tfor (const [index, segment] of parsed.segments.entries()) {\n\t\tconst part = decode(parts[index] ?? '');\n\t\tif (part === undefined || part === '') return undefined;\n\t\tif (segment.kind === 'literal') {\n\t\t\tif (part !== segment.value) return undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tparams[segment.name] = part;\n\t}\n\n\tconst keyParts = parts.slice(parsed.segments.length).map(decode);\n\tif (keyParts.some((part) => part === undefined || part === '..')) {\n\t\treturn undefined;\n\t}\n\tconst key = keyParts.join('/');\n\tif (key === '' || keyParts.includes('')) return undefined;\n\n\treturn { params, key };\n}\n\n/** The path that addresses `key` through the pattern with these parameters. */\nexport function fillPattern(\n\tparsed: ParsedPattern,\n\tparams: Readonly<Record<string, string | number>>,\n\tkey: string,\n): string {\n\tconst head = parsed.segments.map((segment) => {\n\t\tif (segment.kind === 'literal') return segment.value;\n\t\tconst value = params[segment.name];\n\t\tif (value === undefined || `${value}` === '') {\n\t\t\tthrow new ProcessorParamMissing(parsed.pattern, segment.name);\n\t\t}\n\t\treturn encodeURIComponent(`${value}`);\n\t});\n\tconst tail = key\n\t\t.replace(/^\\/+/, '')\n\t\t.split('/')\n\t\t.map((part) => encodeURIComponent(part));\n\n\treturn `/${[...head, ...tail].join('/')}`;\n}\n\n/** A processed URL was asked for without one of the pattern's parameters. */\nexport class ProcessorParamMissing extends Error {\n\tconstructor(\n\t\treadonly pattern: string,\n\t\treadonly param: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${pattern}' needs '${param}' to address an object, and it was not given.`,\n\t\t);\n\t\tthis.name = 'ProcessorParamMissing';\n\t}\n}\n\nfunction decode(part: string): string | undefined {\n\ttry {\n\t\treturn decodeURIComponent(part);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;AAmFA,IAAa,YAAb,cAKU,UAAyC;CAYxC;CACA;CAKA;CAjBV,mBAAmB;CAEnB,OAAO,YAAY,KAAuD;EACzE,OAAO,QACN,OACE,IAAuC,qBAAqB,QAC5D,IAAkB,SAAA,kCACrB;CACD;CAEA,YACC,QACA,SAKA,SAkBC;EACD,MAAA,oCAEC,QAAQ,QAGR,CAAC,QAAQ,QAAQ,GAAG,QAAQ,QAAQ,GACpC,CAAC,GACD,KAAA,GACA,QAAQ,SACR,QAAQ,YACR,KAAA,GAGA,CAAC,mBAAG,IAAI,IAAI,CAAC,QAAQ,UAAU,GAAG,QAAQ,UAAU,CAAC,CAAC,CACvD;EAvCS,KAAA,SAAA;EACA,KAAA,UAAA;EAKA,KAAA,UAAA;EAkCT,KAAK,QAAQ,QAAQ;CACtB;;CAGA,IAAI,UAAoB;EACvB,OAAO,KAAK,OAAO;CACpB;;CAGA,IAAI,SAAiB;EACpB,OAAO,KAAK,OAAO;CACpB;CAEA,IAAI,SAA4B;EAC/B,OAAO,KAAK,QAAQ;CACrB;CAEA,IAAI,YAAoB;EACvB,OAAO,KAAK,QAAQ;CACrB;CAEA,I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;CAEhD,OAAO;EAAE;EAAQ;CAAI;AACtB;;AAGA,SAAgB,YACf,QACA,QACA,KACS;CACT,MAAM,OAAO,OAAO,SAAS,KAAK,YAAY;EAC7C,IAAI,QAAQ,SAAS,WAAW,OAAO,QAAQ;EAC/C,MAAM,QAAQ,OAAO,QAAQ;EAC7B,IAAI,UAAU,KAAA,KAAa,GAAG,YAAY,IACzC,MAAM,IAAI,sBAAsB,OAAO,SAAS,QAAQ,IAAI;EAE7D,OAAO,mBAAmB,GAAG,OAAO;CACrC,CAAC;CACD,MAAM,OAAO,IACX,QAAQ,QAAQ,EAAE,CAAC,CACnB,MAAM,GAAG,CAAC,CACV,KAAK,SAAS,mBAAmB,IAAI,CAAC;CAExC,OAAO,IAAI,CAAC,GAAG,MAAM,GAAG,IAAI,CAAC,CAAC,KAAK,GAAG;AACvC;;AAGA,IAAa,wBAAb,cAA2C,MAAM;CAEtC;CACA;CAFV,YACC,SACA,OACC;EACD,MACC,IAAI,QAAQ,WAAW,MAAM,8CAC9B;EALS,KAAA,UAAA;EACA,KAAA,QAAA;EAKT,KAAK,OAAO;CACb;AACD;AAEA,SAAS,OAAO,MAAkC;CACjD,IAAI;EACH,OAAO,mBAAmB,IAAI;CAC/B,QAAQ;EACP;CACD;AACD"}
1
+ {"version":3,"file":"pattern-C1CEcglD.mjs","names":[],"sources":["../src/processors/Processor.ts","../src/processors/ProcessorBuilder.ts","../src/processors/pattern.ts"],"sourcesContent":["import type { Logger } from '@geekmidas/logger';\nimport type { InferStandardSchema } from '@geekmidas/schema';\nimport type { Service, ServiceRecord } from '@geekmidas/services';\nimport type { ObjectMetadata, StorageClient } from '@geekmidas/storage';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { Construct, ConstructType } from '../Construct';\nimport type { ParsedPattern, PatternParams } from './pattern';\n\n/**\n * Where a processor's results are kept, under its file server's bucket.\n *\n * Written through on every result marked `immutable` and read before the\n * handler runs, so a derivative is made once. Exported so the bucket's expiry\n * can name it.\n */\nexport { DERIVED_PREFIX } from '@geekmidas/manifest';\n\n/** How long a response may be kept, by a browser and by the edge. */\nexport type ProcessorCache =\n\t/** Never changes for these parameters and this key: kept for a year. */\n\t| 'immutable'\n\t/** Kept this many seconds. */\n\t| { maxAge: number }\n\t/** Not kept. */\n\t| 'none';\n\n/** What a processor handler returns. */\nexport interface ProcessorResult {\n\tbody: Uint8Array | string;\n\tcontentType: string;\n\t/**\n\t * `immutable` results are also kept in the bucket, so the next request\n\t * for them never runs the handler. Defaults to an hour, kept nowhere.\n\t */\n\tcache?: ProcessorCache;\n}\n\n/**\n * The object a request addresses, read from the bucket on first use.\n *\n * Its body is one GET, made by the first `bytes()` or `stream()`; what is\n * known about it is one HEAD, made by the first `size()` or `metadata()`.\n * Either throws `ProcessorSourceMissing` when the object is not there, which\n * answers the request with a 404.\n */\nexport interface SourceObject {\n\treadonly key: string;\n\t/** Its size in bytes, from a HEAD: the body is not downloaded. */\n\tsize(): Promise<number>;\n\t/** Everything a HEAD answers, without downloading the body. */\n\tmetadata(): Promise<ObjectMetadata>;\n\tbytes(): Promise<Uint8Array>;\n\tstream(): Promise<ReadableStream<Uint8Array>>;\n\t/**\n\t * The type it was stored with: from the body's response when it has\n\t * already been read, otherwise from a HEAD.\n\t */\n\tcontentType(): Promise<string | undefined>;\n}\n\nexport interface ProcessorContext<\n\tTParams,\n\tTServices extends Service[],\n\tTLogger extends Logger,\n> {\n\tparams: TParams;\n\tkey: string;\n\tobject: SourceObject;\n\tlogger: TLogger;\n\tservices: ServiceRecord<TServices>;\n}\n\nexport type ProcessorHandler<\n\tTParams,\n\tTServices extends Service[],\n\tTLogger extends Logger,\n> = (\n\tcontext: ProcessorContext<TParams, TServices, TLogger>,\n) => Promise<ProcessorResult> | ProcessorResult;\n\n/** What a processor's parameters parse to: its schema's output, or the raw strings. */\nexport type ProcessorParams<\n\tTPattern extends string,\n\tTSchema extends StandardSchemaV1 | undefined,\n> = TSchema extends StandardSchemaV1\n\t? InferStandardSchema<TSchema>\n\t: PatternParams<TPattern>;\n\n/**\n * A processor — a handler behind one path pattern of a file server, which\n * makes a derivative of an open object on read: a thumbnail, a page of a PDF.\n *\n * Built from the file server (`assets.process('/i/:width/*')`), so it carries\n * the bucket it reads and the open paths it may serve. Its parameters' schema\n * is the allowlist: a request outside it is refused before anything runs, so\n * nobody can mint new work — or new cache entries — by varying a number.\n */\nexport class Processor<\n\tTPattern extends string = string,\n\tTSchema extends StandardSchemaV1 | undefined = undefined,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n> extends Construct<TLogger, undefined, TServices> {\n\t__IS_PROCESSOR__ = true;\n\n\tstatic isProcessor(obj: unknown): obj is Processor<string, any, any, any> {\n\t\treturn Boolean(\n\t\t\tobj &&\n\t\t\t\t(obj as { __IS_PROCESSOR__?: boolean }).__IS_PROCESSOR__ === true &&\n\t\t\t\t(obj as Construct).type === ConstructType.Processor,\n\t\t);\n\t}\n\n\tconstructor(\n\t\treadonly parsed: ParsedPattern,\n\t\treadonly handler: ProcessorHandler<\n\t\t\tProcessorParams<TPattern, TSchema>,\n\t\t\tTServices,\n\t\t\tTLogger\n\t\t>,\n\t\treadonly options: {\n\t\t\t/** The file server's surface id — the unit that runs it. */\n\t\t\tsurfaceId: string;\n\t\t\t/** The bucket it reads from and keeps derivatives in. */\n\t\t\tbucketId: string;\n\t\t\t/** How it reaches that bucket. */\n\t\t\torigin: Service<string, StorageClient>;\n\t\t\t/** Whether a key is one of the file server's open paths. */\n\t\t\tserves: (key: string) => boolean;\n\t\t\tparamsSchema?: TSchema;\n\t\t\t/** Packages with native code, installed for the target. */\n\t\t\tnative: readonly string[];\n\t\t\tlogger: TLogger;\n\t\t\tservices: TServices;\n\t\t\tconstructs: string[];\n\t\t\ttimeout?: number;\n\t\t\tmemorySize?: number;\n\t\t},\n\t) {\n\t\tsuper(\n\t\t\tConstructType.Processor,\n\t\t\toptions.logger,\n\t\t\t// The bucket is reached like any service — which is also how its URL\n\t\t\t// is found by the environment sniffer.\n\t\t\t[options.origin, ...options.services] as unknown as TServices,\n\t\t\t[],\n\t\t\tundefined,\n\t\t\toptions.timeout,\n\t\t\toptions.memorySize,\n\t\t\tundefined,\n\t\t\t// The bucket is an edge of its process, so the unit running it is\n\t\t\t// handed the bucket's address.\n\t\t\t[...new Set([options.bucketId, ...options.constructs])],\n\t\t);\n\t\tthis.owner = options.surfaceId;\n\t}\n\n\t/** The pattern it answers, as written. */\n\tget pattern(): TPattern {\n\t\treturn this.parsed.pattern as TPattern;\n\t}\n\n\t/** The literal path the edge routes to it — `/i/`. */\n\tget prefix(): string {\n\t\treturn this.parsed.prefix;\n\t}\n\n\tget native(): readonly string[] {\n\t\treturn this.options.native;\n\t}\n\n\tget surfaceId(): string {\n\t\treturn this.options.surfaceId;\n\t}\n\n\tget bucketId(): string {\n\t\treturn this.options.bucketId;\n\t}\n}\n","import type { Logger } from '@geekmidas/logger';\nimport type { Service } from '@geekmidas/services';\nimport type { StorageClient } from '@geekmidas/storage';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport {\n\ttype Consumable,\n\tidsOf,\n\ttype ServicesOf,\n\tservicesOf,\n} from '../construct-interface';\nimport {\n\tProcessor,\n\ttype ProcessorHandler,\n\ttype ProcessorParams,\n} from './Processor';\nimport type { ParsedPattern } from './pattern';\n\n/** A native package named in a way no installer could resolve. */\nexport class ProcessorNativeInvalid extends Error {\n\tconstructor(readonly packageName: string) {\n\t\tsuper(\n\t\t\t`'${packageName}' is not a package name. Name the package with native code ` +\n\t\t\t\t`as it is installed — 'sharp', '@napi-rs/canvas' — and its version ` +\n\t\t\t\t`is taken from the app's package.json.`,\n\t\t);\n\t\tthis.name = 'ProcessorNativeInvalid';\n\t}\n}\n\ninterface ProcessorBuilderState<TLogger extends Logger> {\n\tparsed: ParsedPattern;\n\tsurfaceId: string;\n\tbucketId: string;\n\torigin: Service<string, StorageClient>;\n\tserves: (key: string) => boolean;\n\tlogger: TLogger;\n\tparamsSchema?: StandardSchemaV1;\n\tnative: string[];\n\tservices: Service[];\n\tconstructs: string[];\n\ttimeout?: number;\n\tmemorySize?: number;\n}\n\n/**\n * What `fileServer.process(pattern)` returns: a processor, built up one\n * immutable step at a time and finished by `.handle()`.\n */\nexport class ProcessorBuilder<\n\tTPattern extends string,\n\tTSchema extends StandardSchemaV1 | undefined = undefined,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n> {\n\tconstructor(private readonly state: ProcessorBuilderState<TLogger>) {}\n\n\t/**\n\t * The parameters' schema — the allowlist. Every request is parsed by it\n\t * before anything runs, and one it refuses is answered 400.\n\t */\n\tparams<T extends StandardSchemaV1>(\n\t\tschema: T,\n\t): ProcessorBuilder<TPattern, T, TServices, TLogger> {\n\t\treturn new ProcessorBuilder({ ...this.state, paramsSchema: schema });\n\t}\n\n\t/** Constructs its handler reaches, as `services.<id>`. */\n\tdependsOn<const T extends readonly Consumable[]>(\n\t\tconstructs: T,\n\t): ProcessorBuilder<\n\t\tTPattern,\n\t\tTSchema,\n\t\t[...TServices, ...ServicesOf<T>],\n\t\tTLogger\n\t> {\n\t\tconst services = servicesOf(constructs) as unknown as Service[];\n\t\treturn new ProcessorBuilder({\n\t\t\t...this.state,\n\t\t\tservices: [\n\t\t\t\t...this.state.services.filter(\n\t\t\t\t\t(service) =>\n\t\t\t\t\t\t!services.some((s) => s.serviceName === service.serviceName),\n\t\t\t\t),\n\t\t\t\t...services,\n\t\t\t],\n\t\t\tconstructs: idsOf(constructs, this.state.constructs),\n\t\t});\n\t}\n\n\t/**\n\t * Packages with native code — `sharp` — installed for the target the\n\t * processor runs on rather than bundled: linux in its image, arm64 on\n\t * Lambda.\n\t */\n\tnative(packages: readonly string[]): this {\n\t\tfor (const name of packages) {\n\t\t\tif (!/^(@[a-z0-9._~-]+\\/)?[a-z0-9._~-]+$/.test(name)) {\n\t\t\t\tthrow new ProcessorNativeInvalid(name);\n\t\t\t}\n\t\t}\n\t\treturn new ProcessorBuilder({\n\t\t\t...this.state,\n\t\t\tnative: [...new Set([...this.state.native, ...packages])],\n\t\t}) as this;\n\t}\n\n\t/** Milliseconds a request may take, where the target bounds it. */\n\ttimeout(ms: number): this {\n\t\treturn new ProcessorBuilder({ ...this.state, timeout: ms }) as this;\n\t}\n\n\t/** Megabytes of memory, where the target sets it. */\n\tmemorySize(mb: number): this {\n\t\treturn new ProcessorBuilder({ ...this.state, memorySize: mb }) as this;\n\t}\n\n\thandle(\n\t\tfn: ProcessorHandler<\n\t\t\tProcessorParams<TPattern, TSchema>,\n\t\t\tTServices,\n\t\t\tTLogger\n\t\t>,\n\t): Processor<TPattern, TSchema, TServices, TLogger> {\n\t\tconst { state } = this;\n\t\treturn new Processor<TPattern, TSchema, TServices, TLogger>(\n\t\t\tstate.parsed,\n\t\t\tfn,\n\t\t\t{\n\t\t\t\tsurfaceId: state.surfaceId,\n\t\t\t\tbucketId: state.bucketId,\n\t\t\t\torigin: state.origin,\n\t\t\t\tserves: state.serves,\n\t\t\t\t...(state.paramsSchema\n\t\t\t\t\t? { paramsSchema: state.paramsSchema as TSchema }\n\t\t\t\t\t: {}),\n\t\t\t\tnative: state.native,\n\t\t\t\tlogger: state.logger,\n\t\t\t\tservices: state.services as TServices,\n\t\t\t\tconstructs: state.constructs,\n\t\t\t\t...(state.timeout !== undefined ? { timeout: state.timeout } : {}),\n\t\t\t\t...(state.memorySize !== undefined\n\t\t\t\t\t? { memorySize: state.memorySize }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t);\n\t}\n}\n","/**\n * A processor's path pattern: literal segments, `:name` parameters, and a\n * final `*` that is the object's key.\n *\n * ```\n * /i/:width/* → /i/256/avatars/7.png { width: '256' }, 'avatars/7.png'\n * /pdf/:page/:dpi/* → /pdf/1/150/doc.pdf { page: '1', dpi: '150' }, 'doc.pdf'\n * ```\n *\n * It starts with a literal segment because the edge routes on that prefix: a\n * pattern beginning with a parameter would claim every path on the file\n * server, objects included.\n */\n\n/** The parameter names a pattern declares, as a union. */\nexport type PatternParamNames<P extends string> =\n\tP extends `${string}/:${infer Name}/${infer Rest}`\n\t\t? Name | PatternParamNames<`/${Rest}`>\n\t\t: never;\n\n/** The raw parameters a pattern matches, before its schema parses them. */\nexport type PatternParams<P extends string> = {\n\t[K in PatternParamNames<P>]: string;\n};\n\n/** A pattern a processor cannot be served on. */\nexport class ProcessorPatternInvalid extends Error {\n\tconstructor(\n\t\treadonly pattern: string,\n\t\treadonly reason: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${pattern}' is not a processor pattern: ${reason}. A pattern is a ` +\n\t\t\t\t`literal first segment, then any \\`:name\\` parameters, then \\`*\\` ` +\n\t\t\t\t`for the object's key — '/i/:width/*'.`,\n\t\t);\n\t\tthis.name = 'ProcessorPatternInvalid';\n\t}\n}\n\n/** A pattern, parsed once. */\nexport interface ParsedPattern {\n\treadonly pattern: string;\n\t/** Each segment before the key: a literal, or a parameter's name. */\n\treadonly segments: readonly (\n\t\t| { kind: 'literal'; value: string }\n\t\t| { kind: 'param'; name: string }\n\t)[];\n\t/** The parameter names, in the order they appear. */\n\treadonly params: readonly string[];\n\t/** The literal path the edge routes on — `/i/`. */\n\treadonly prefix: string;\n}\n\n/** @throws {ProcessorPatternInvalid} */\nexport function parsePattern(pattern: string): ParsedPattern {\n\tif (!pattern.startsWith('/')) {\n\t\tthrow new ProcessorPatternInvalid(pattern, 'it does not start with /');\n\t}\n\tif (!pattern.endsWith('/*')) {\n\t\tthrow new ProcessorPatternInvalid(\n\t\t\tpattern,\n\t\t\t'it does not end with /* — the key',\n\t\t);\n\t}\n\n\tconst parts = pattern.slice(1, -2).split('/');\n\tconst segments: ParsedPattern['segments'][number][] = [];\n\tconst params: string[] = [];\n\tfor (const part of parts) {\n\t\tif (part === '') {\n\t\t\tthrow new ProcessorPatternInvalid(pattern, 'it has an empty segment');\n\t\t}\n\t\tif (part.includes('*')) {\n\t\t\tthrow new ProcessorPatternInvalid(\n\t\t\t\tpattern,\n\t\t\t\t'only its last segment may be *',\n\t\t\t);\n\t\t}\n\t\tif (part.startsWith(':')) {\n\t\t\tconst name = part.slice(1);\n\t\t\tif (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {\n\t\t\t\tthrow new ProcessorPatternInvalid(\n\t\t\t\t\tpattern,\n\t\t\t\t\t`'${part}' is not a parameter name`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (params.includes(name)) {\n\t\t\t\tthrow new ProcessorPatternInvalid(pattern, `'${name}' appears twice`);\n\t\t\t}\n\t\t\tparams.push(name);\n\t\t\tsegments.push({ kind: 'param', name });\n\t\t\tcontinue;\n\t\t}\n\t\tif (!/^[A-Za-z0-9._~-]+$/.test(part)) {\n\t\t\tthrow new ProcessorPatternInvalid(\n\t\t\t\tpattern,\n\t\t\t\t`'${part}' has characters a path segment would escape`,\n\t\t\t);\n\t\t}\n\t\tsegments.push({ kind: 'literal', value: part });\n\t}\n\n\tconst first = segments[0];\n\tif (!first || first.kind !== 'literal') {\n\t\tthrow new ProcessorPatternInvalid(\n\t\t\tpattern,\n\t\t\t'its first segment is a parameter, which would claim every path',\n\t\t);\n\t}\n\n\tconst literals: string[] = [];\n\tfor (const segment of segments) {\n\t\tif (segment.kind !== 'literal') break;\n\t\tliterals.push(segment.value);\n\t}\n\n\treturn { pattern, segments, params, prefix: `/${literals.join('/')}/` };\n}\n\n/** A path the pattern matched: its raw parameters and the key. */\nexport interface PatternMatch {\n\tparams: Record<string, string>;\n\tkey: string;\n}\n\n/**\n * Match a request path, decoding each parameter and each key segment. A path\n * with an empty key, or one that decodes to a `..` segment, matches nothing.\n */\nexport function matchPattern(\n\tparsed: ParsedPattern,\n\tpath: string,\n): PatternMatch | undefined {\n\tconst parts = path.replace(/^\\/+/, '').split('/');\n\tif (parts.length <= parsed.segments.length) return undefined;\n\n\tconst params: Record<string, string> = {};\n\tfor (const [index, segment] of parsed.segments.entries()) {\n\t\tconst part = decode(parts[index] ?? '');\n\t\tif (part === undefined || part === '') return undefined;\n\t\tif (segment.kind === 'literal') {\n\t\t\tif (part !== segment.value) return undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tparams[segment.name] = part;\n\t}\n\n\tconst keyParts = parts.slice(parsed.segments.length).map(decode);\n\tif (keyParts.some((part) => part === undefined || part === '..')) {\n\t\treturn undefined;\n\t}\n\tconst key = keyParts.join('/');\n\tif (key === '' || keyParts.includes('')) return undefined;\n\n\treturn { params, key };\n}\n\n/** The path that addresses `key` through the pattern with these parameters. */\nexport function fillPattern(\n\tparsed: ParsedPattern,\n\tparams: Readonly<Record<string, string | number>>,\n\tkey: string,\n): string {\n\tconst head = parsed.segments.map((segment) => {\n\t\tif (segment.kind === 'literal') return segment.value;\n\t\tconst value = params[segment.name];\n\t\tif (value === undefined || `${value}` === '') {\n\t\t\tthrow new ProcessorParamMissing(parsed.pattern, segment.name);\n\t\t}\n\t\treturn encodeURIComponent(`${value}`);\n\t});\n\tconst tail = key\n\t\t.replace(/^\\/+/, '')\n\t\t.split('/')\n\t\t.map((part) => encodeURIComponent(part));\n\n\treturn `/${[...head, ...tail].join('/')}`;\n}\n\n/** A processed URL was asked for without one of the pattern's parameters. */\nexport class ProcessorParamMissing extends Error {\n\tconstructor(\n\t\treadonly pattern: string,\n\t\treadonly param: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${pattern}' needs '${param}' to address an object, and it was not given.`,\n\t\t);\n\t\tthis.name = 'ProcessorParamMissing';\n\t}\n}\n\nfunction decode(part: string): string | undefined {\n\ttry {\n\t\treturn decodeURIComponent(part);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;AAiGA,IAAa,YAAb,cAKU,UAAyC;CAYxC;CACA;CAKA;CAjBV,mBAAmB;CAEnB,OAAO,YAAY,KAAuD;EACzE,OAAO,QACN,OACE,IAAuC,qBAAqB,QAC5D,IAAkB,SAAA,kCACrB;CACD;CAEA,YACC,QACA,SAKA,SAkBC;EACD,MAAA,oCAEC,QAAQ,QAGR,CAAC,QAAQ,QAAQ,GAAG,QA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ACD;AACD"}
@@ -1 +1 @@
1
- {"version":3,"file":"pattern-QFaUIr77.cjs","names":["Construct","servicesOf","idsOf"],"sources":["../src/processors/Processor.ts","../src/processors/ProcessorBuilder.ts","../src/processors/pattern.ts"],"sourcesContent":["import type { Logger } from '@geekmidas/logger';\nimport type { InferStandardSchema } from '@geekmidas/schema';\nimport type { Service, ServiceRecord } from '@geekmidas/services';\nimport type { StorageClient } from '@geekmidas/storage';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { Construct, ConstructType } from '../Construct';\nimport type { ParsedPattern, PatternParams } from './pattern';\n\n/**\n * Where a processor's results are kept, under its file server's bucket.\n *\n * Written through on every result marked `immutable` and read before the\n * handler runs, so a derivative is made once. Exported so the bucket's expiry\n * can name it.\n */\nexport { DERIVED_PREFIX } from '@geekmidas/manifest';\n\n/** How long a response may be kept, by a browser and by the edge. */\nexport type ProcessorCache =\n\t/** Never changes for these parameters and this key: kept for a year. */\n\t| 'immutable'\n\t/** Kept this many seconds. */\n\t| { maxAge: number }\n\t/** Not kept. */\n\t| 'none';\n\n/** What a processor handler returns. */\nexport interface ProcessorResult {\n\tbody: Uint8Array | string;\n\tcontentType: string;\n\t/**\n\t * `immutable` results are also kept in the bucket, so the next request\n\t * for them never runs the handler. Defaults to an hour, kept nowhere.\n\t */\n\tcache?: ProcessorCache;\n}\n\n/** The object a request addresses, read from the bucket on first use. */\nexport interface SourceObject {\n\treadonly key: string;\n\tbytes(): Promise<Uint8Array>;\n\tstream(): Promise<ReadableStream<Uint8Array>>;\n\t/** The type it was stored with. */\n\tcontentType(): Promise<string | undefined>;\n}\n\nexport interface ProcessorContext<\n\tTParams,\n\tTServices extends Service[],\n\tTLogger extends Logger,\n> {\n\tparams: TParams;\n\tkey: string;\n\tobject: SourceObject;\n\tlogger: TLogger;\n\tservices: ServiceRecord<TServices>;\n}\n\nexport type ProcessorHandler<\n\tTParams,\n\tTServices extends Service[],\n\tTLogger extends Logger,\n> = (\n\tcontext: ProcessorContext<TParams, TServices, TLogger>,\n) => Promise<ProcessorResult> | ProcessorResult;\n\n/** What a processor's parameters parse to: its schema's output, or the raw strings. */\nexport type ProcessorParams<\n\tTPattern extends string,\n\tTSchema extends StandardSchemaV1 | undefined,\n> = TSchema extends StandardSchemaV1\n\t? InferStandardSchema<TSchema>\n\t: PatternParams<TPattern>;\n\n/**\n * A processor — a handler behind one path pattern of a file server, which\n * makes a derivative of an open object on read: a thumbnail, a page of a PDF.\n *\n * Built from the file server (`assets.process('/i/:width/*')`), so it carries\n * the bucket it reads and the open paths it may serve. Its parameters' schema\n * is the allowlist: a request outside it is refused before anything runs, so\n * nobody can mint new work — or new cache entries — by varying a number.\n */\nexport class Processor<\n\tTPattern extends string = string,\n\tTSchema extends StandardSchemaV1 | undefined = undefined,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n> extends Construct<TLogger, undefined, TServices> {\n\t__IS_PROCESSOR__ = true;\n\n\tstatic isProcessor(obj: unknown): obj is Processor<string, any, any, any> {\n\t\treturn Boolean(\n\t\t\tobj &&\n\t\t\t\t(obj as { __IS_PROCESSOR__?: boolean }).__IS_PROCESSOR__ === true &&\n\t\t\t\t(obj as Construct).type === ConstructType.Processor,\n\t\t);\n\t}\n\n\tconstructor(\n\t\treadonly parsed: ParsedPattern,\n\t\treadonly handler: ProcessorHandler<\n\t\t\tProcessorParams<TPattern, TSchema>,\n\t\t\tTServices,\n\t\t\tTLogger\n\t\t>,\n\t\treadonly options: {\n\t\t\t/** The file server's surface id — the unit that runs it. */\n\t\t\tsurfaceId: string;\n\t\t\t/** The bucket it reads from and keeps derivatives in. */\n\t\t\tbucketId: string;\n\t\t\t/** How it reaches that bucket. */\n\t\t\torigin: Service<string, StorageClient>;\n\t\t\t/** Whether a key is one of the file server's open paths. */\n\t\t\tserves: (key: string) => boolean;\n\t\t\tparamsSchema?: TSchema;\n\t\t\t/** Packages with native code, installed for the target. */\n\t\t\tnative: readonly string[];\n\t\t\tlogger: TLogger;\n\t\t\tservices: TServices;\n\t\t\tconstructs: string[];\n\t\t\ttimeout?: number;\n\t\t\tmemorySize?: number;\n\t\t},\n\t) {\n\t\tsuper(\n\t\t\tConstructType.Processor,\n\t\t\toptions.logger,\n\t\t\t// The bucket is reached like any service — which is also how its URL\n\t\t\t// is found by the environment sniffer.\n\t\t\t[options.origin, ...options.services] as unknown as TServices,\n\t\t\t[],\n\t\t\tundefined,\n\t\t\toptions.timeout,\n\t\t\toptions.memorySize,\n\t\t\tundefined,\n\t\t\t// The bucket is an edge of its process, so the unit running it is\n\t\t\t// handed the bucket's address.\n\t\t\t[...new Set([options.bucketId, ...options.constructs])],\n\t\t);\n\t\tthis.owner = options.surfaceId;\n\t}\n\n\t/** The pattern it answers, as written. */\n\tget pattern(): TPattern {\n\t\treturn this.parsed.pattern as TPattern;\n\t}\n\n\t/** The literal path the edge routes to it — `/i/`. */\n\tget prefix(): string {\n\t\treturn this.parsed.prefix;\n\t}\n\n\tget native(): readonly string[] {\n\t\treturn this.options.native;\n\t}\n\n\tget surfaceId(): string {\n\t\treturn this.options.surfaceId;\n\t}\n\n\tget bucketId(): string {\n\t\treturn this.options.bucketId;\n\t}\n}\n","import type { Logger } from '@geekmidas/logger';\nimport type { Service } from '@geekmidas/services';\nimport type { StorageClient } from '@geekmidas/storage';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport {\n\ttype Consumable,\n\tidsOf,\n\ttype ServicesOf,\n\tservicesOf,\n} from '../construct-interface';\nimport {\n\tProcessor,\n\ttype ProcessorHandler,\n\ttype ProcessorParams,\n} from './Processor';\nimport type { ParsedPattern } from './pattern';\n\n/** A native package named in a way no installer could resolve. */\nexport class ProcessorNativeInvalid extends Error {\n\tconstructor(readonly packageName: string) {\n\t\tsuper(\n\t\t\t`'${packageName}' is not a package name. Name the package with native code ` +\n\t\t\t\t`as it is installed — 'sharp', '@napi-rs/canvas' — and its version ` +\n\t\t\t\t`is taken from the app's package.json.`,\n\t\t);\n\t\tthis.name = 'ProcessorNativeInvalid';\n\t}\n}\n\ninterface ProcessorBuilderState<TLogger extends Logger> {\n\tparsed: ParsedPattern;\n\tsurfaceId: string;\n\tbucketId: string;\n\torigin: Service<string, StorageClient>;\n\tserves: (key: string) => boolean;\n\tlogger: TLogger;\n\tparamsSchema?: StandardSchemaV1;\n\tnative: string[];\n\tservices: Service[];\n\tconstructs: string[];\n\ttimeout?: number;\n\tmemorySize?: number;\n}\n\n/**\n * What `fileServer.process(pattern)` returns: a processor, built up one\n * immutable step at a time and finished by `.handle()`.\n */\nexport class ProcessorBuilder<\n\tTPattern extends string,\n\tTSchema extends StandardSchemaV1 | undefined = undefined,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n> {\n\tconstructor(private readonly state: ProcessorBuilderState<TLogger>) {}\n\n\t/**\n\t * The parameters' schema — the allowlist. Every request is parsed by it\n\t * before anything runs, and one it refuses is answered 400.\n\t */\n\tparams<T extends StandardSchemaV1>(\n\t\tschema: T,\n\t): ProcessorBuilder<TPattern, T, TServices, TLogger> {\n\t\treturn new ProcessorBuilder({ ...this.state, paramsSchema: schema });\n\t}\n\n\t/** Constructs its handler reaches, as `services.<id>`. */\n\tdependsOn<const T extends readonly Consumable[]>(\n\t\tconstructs: T,\n\t): ProcessorBuilder<\n\t\tTPattern,\n\t\tTSchema,\n\t\t[...TServices, ...ServicesOf<T>],\n\t\tTLogger\n\t> {\n\t\tconst services = servicesOf(constructs) as unknown as Service[];\n\t\treturn new ProcessorBuilder({\n\t\t\t...this.state,\n\t\t\tservices: [\n\t\t\t\t...this.state.services.filter(\n\t\t\t\t\t(service) =>\n\t\t\t\t\t\t!services.some((s) => s.serviceName === service.serviceName),\n\t\t\t\t),\n\t\t\t\t...services,\n\t\t\t],\n\t\t\tconstructs: idsOf(constructs, this.state.constructs),\n\t\t});\n\t}\n\n\t/**\n\t * Packages with native code — `sharp` — installed for the target the\n\t * processor runs on rather than bundled: linux in its image, arm64 on\n\t * Lambda.\n\t */\n\tnative(packages: readonly string[]): this {\n\t\tfor (const name of packages) {\n\t\t\tif (!/^(@[a-z0-9._~-]+\\/)?[a-z0-9._~-]+$/.test(name)) {\n\t\t\t\tthrow new ProcessorNativeInvalid(name);\n\t\t\t}\n\t\t}\n\t\treturn new ProcessorBuilder({\n\t\t\t...this.state,\n\t\t\tnative: [...new Set([...this.state.native, ...packages])],\n\t\t}) as this;\n\t}\n\n\t/** Milliseconds a request may take, where the target bounds it. */\n\ttimeout(ms: number): this {\n\t\treturn new ProcessorBuilder({ ...this.state, timeout: ms }) as this;\n\t}\n\n\t/** Megabytes of memory, where the target sets it. */\n\tmemorySize(mb: number): this {\n\t\treturn new ProcessorBuilder({ ...this.state, memorySize: mb }) as this;\n\t}\n\n\thandle(\n\t\tfn: ProcessorHandler<\n\t\t\tProcessorParams<TPattern, TSchema>,\n\t\t\tTServices,\n\t\t\tTLogger\n\t\t>,\n\t): Processor<TPattern, TSchema, TServices, TLogger> {\n\t\tconst { state } = this;\n\t\treturn new Processor<TPattern, TSchema, TServices, TLogger>(\n\t\t\tstate.parsed,\n\t\t\tfn,\n\t\t\t{\n\t\t\t\tsurfaceId: state.surfaceId,\n\t\t\t\tbucketId: state.bucketId,\n\t\t\t\torigin: state.origin,\n\t\t\t\tserves: state.serves,\n\t\t\t\t...(state.paramsSchema\n\t\t\t\t\t? { paramsSchema: state.paramsSchema as TSchema }\n\t\t\t\t\t: {}),\n\t\t\t\tnative: state.native,\n\t\t\t\tlogger: state.logger,\n\t\t\t\tservices: state.services as TServices,\n\t\t\t\tconstructs: state.constructs,\n\t\t\t\t...(state.timeout !== undefined ? { timeout: state.timeout } : {}),\n\t\t\t\t...(state.memorySize !== undefined\n\t\t\t\t\t? { memorySize: state.memorySize }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t);\n\t}\n}\n","/**\n * A processor's path pattern: literal segments, `:name` parameters, and a\n * final `*` that is the object's key.\n *\n * ```\n * /i/:width/* → /i/256/avatars/7.png { width: '256' }, 'avatars/7.png'\n * /pdf/:page/:dpi/* → /pdf/1/150/doc.pdf { page: '1', dpi: '150' }, 'doc.pdf'\n * ```\n *\n * It starts with a literal segment because the edge routes on that prefix: a\n * pattern beginning with a parameter would claim every path on the file\n * server, objects included.\n */\n\n/** The parameter names a pattern declares, as a union. */\nexport type PatternParamNames<P extends string> =\n\tP extends `${string}/:${infer Name}/${infer Rest}`\n\t\t? Name | PatternParamNames<`/${Rest}`>\n\t\t: never;\n\n/** The raw parameters a pattern matches, before its schema parses them. */\nexport type PatternParams<P extends string> = {\n\t[K in PatternParamNames<P>]: string;\n};\n\n/** A pattern a processor cannot be served on. */\nexport class ProcessorPatternInvalid extends Error {\n\tconstructor(\n\t\treadonly pattern: string,\n\t\treadonly reason: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${pattern}' is not a processor pattern: ${reason}. A pattern is a ` +\n\t\t\t\t`literal first segment, then any \\`:name\\` parameters, then \\`*\\` ` +\n\t\t\t\t`for the object's key — '/i/:width/*'.`,\n\t\t);\n\t\tthis.name = 'ProcessorPatternInvalid';\n\t}\n}\n\n/** A pattern, parsed once. */\nexport interface ParsedPattern {\n\treadonly pattern: string;\n\t/** Each segment before the key: a literal, or a parameter's name. */\n\treadonly segments: readonly (\n\t\t| { kind: 'literal'; value: string }\n\t\t| { kind: 'param'; name: string }\n\t)[];\n\t/** The parameter names, in the order they appear. */\n\treadonly params: readonly string[];\n\t/** The literal path the edge routes on — `/i/`. */\n\treadonly prefix: string;\n}\n\n/** @throws {ProcessorPatternInvalid} */\nexport function parsePattern(pattern: string): ParsedPattern {\n\tif (!pattern.startsWith('/')) {\n\t\tthrow new ProcessorPatternInvalid(pattern, 'it does not start with /');\n\t}\n\tif (!pattern.endsWith('/*')) {\n\t\tthrow new ProcessorPatternInvalid(\n\t\t\tpattern,\n\t\t\t'it does not end with /* — the key',\n\t\t);\n\t}\n\n\tconst parts = pattern.slice(1, -2).split('/');\n\tconst segments: ParsedPattern['segments'][number][] = [];\n\tconst params: string[] = [];\n\tfor (const part of parts) {\n\t\tif (part === '') {\n\t\t\tthrow new ProcessorPatternInvalid(pattern, 'it has an empty segment');\n\t\t}\n\t\tif (part.includes('*')) {\n\t\t\tthrow new ProcessorPatternInvalid(\n\t\t\t\tpattern,\n\t\t\t\t'only its last segment may be *',\n\t\t\t);\n\t\t}\n\t\tif (part.startsWith(':')) {\n\t\t\tconst name = part.slice(1);\n\t\t\tif (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {\n\t\t\t\tthrow new ProcessorPatternInvalid(\n\t\t\t\t\tpattern,\n\t\t\t\t\t`'${part}' is not a parameter name`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (params.includes(name)) {\n\t\t\t\tthrow new ProcessorPatternInvalid(pattern, `'${name}' appears twice`);\n\t\t\t}\n\t\t\tparams.push(name);\n\t\t\tsegments.push({ kind: 'param', name });\n\t\t\tcontinue;\n\t\t}\n\t\tif (!/^[A-Za-z0-9._~-]+$/.test(part)) {\n\t\t\tthrow new ProcessorPatternInvalid(\n\t\t\t\tpattern,\n\t\t\t\t`'${part}' has characters a path segment would escape`,\n\t\t\t);\n\t\t}\n\t\tsegments.push({ kind: 'literal', value: part });\n\t}\n\n\tconst first = segments[0];\n\tif (!first || first.kind !== 'literal') {\n\t\tthrow new ProcessorPatternInvalid(\n\t\t\tpattern,\n\t\t\t'its first segment is a parameter, which would claim every path',\n\t\t);\n\t}\n\n\tconst literals: string[] = [];\n\tfor (const segment of segments) {\n\t\tif (segment.kind !== 'literal') break;\n\t\tliterals.push(segment.value);\n\t}\n\n\treturn { pattern, segments, params, prefix: `/${literals.join('/')}/` };\n}\n\n/** A path the pattern matched: its raw parameters and the key. */\nexport interface PatternMatch {\n\tparams: Record<string, string>;\n\tkey: string;\n}\n\n/**\n * Match a request path, decoding each parameter and each key segment. A path\n * with an empty key, or one that decodes to a `..` segment, matches nothing.\n */\nexport function matchPattern(\n\tparsed: ParsedPattern,\n\tpath: string,\n): PatternMatch | undefined {\n\tconst parts = path.replace(/^\\/+/, '').split('/');\n\tif (parts.length <= parsed.segments.length) return undefined;\n\n\tconst params: Record<string, string> = {};\n\tfor (const [index, segment] of parsed.segments.entries()) {\n\t\tconst part = decode(parts[index] ?? '');\n\t\tif (part === undefined || part === '') return undefined;\n\t\tif (segment.kind === 'literal') {\n\t\t\tif (part !== segment.value) return undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tparams[segment.name] = part;\n\t}\n\n\tconst keyParts = parts.slice(parsed.segments.length).map(decode);\n\tif (keyParts.some((part) => part === undefined || part === '..')) {\n\t\treturn undefined;\n\t}\n\tconst key = keyParts.join('/');\n\tif (key === '' || keyParts.includes('')) return undefined;\n\n\treturn { params, key };\n}\n\n/** The path that addresses `key` through the pattern with these parameters. */\nexport function fillPattern(\n\tparsed: ParsedPattern,\n\tparams: Readonly<Record<string, string | number>>,\n\tkey: string,\n): string {\n\tconst head = parsed.segments.map((segment) => {\n\t\tif (segment.kind === 'literal') return segment.value;\n\t\tconst value = params[segment.name];\n\t\tif (value === undefined || `${value}` === '') {\n\t\t\tthrow new ProcessorParamMissing(parsed.pattern, segment.name);\n\t\t}\n\t\treturn encodeURIComponent(`${value}`);\n\t});\n\tconst tail = key\n\t\t.replace(/^\\/+/, '')\n\t\t.split('/')\n\t\t.map((part) => encodeURIComponent(part));\n\n\treturn `/${[...head, ...tail].join('/')}`;\n}\n\n/** A processed URL was asked for without one of the pattern's parameters. */\nexport class ProcessorParamMissing extends Error {\n\tconstructor(\n\t\treadonly pattern: string,\n\t\treadonly param: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${pattern}' needs '${param}' to address an object, and it was not given.`,\n\t\t);\n\t\tthis.name = 'ProcessorParamMissing';\n\t}\n}\n\nfunction decode(part: string): string | undefined {\n\ttry {\n\t\treturn decodeURIComponent(part);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;AAmFA,IAAa,YAAb,cAKUA,kBAAAA,UAAyC;CAYxC;CACA;CAKA;CA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EtC;CACA;CAFV,YACC,SACA,OACC;EACD,MACC,IAAI,QAAQ,WAAW,MAAM,8CAC9B;EALS,KAAA,UAAA;EACA,KAAA,QAAA;EAKT,KAAK,OAAO;CACb;AACD;AAEA,SAAS,OAAO,MAAkC;CACjD,IAAI;EACH,OAAO,mBAAmB,IAAI;CAC/B,QAAQ;EACP;CACD;AACD"}
1
+ {"version":3,"file":"pattern-QFaUIr77.cjs","names":["Construct","servicesOf","idsOf"],"sources":["../src/processors/Processor.ts","../src/processors/ProcessorBuilder.ts","../src/processors/pattern.ts"],"sourcesContent":["import type { Logger } from '@geekmidas/logger';\nimport type { InferStandardSchema } from '@geekmidas/schema';\nimport type { Service, ServiceRecord } from '@geekmidas/services';\nimport type { ObjectMetadata, StorageClient } from '@geekmidas/storage';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { Construct, ConstructType } from '../Construct';\nimport type { ParsedPattern, PatternParams } from './pattern';\n\n/**\n * Where a processor's results are kept, under its file server's bucket.\n *\n * Written through on every result marked `immutable` and read before the\n * handler runs, so a derivative is made once. Exported so the bucket's expiry\n * can name it.\n */\nexport { DERIVED_PREFIX } from '@geekmidas/manifest';\n\n/** How long a response may be kept, by a browser and by the edge. */\nexport type ProcessorCache =\n\t/** Never changes for these parameters and this key: kept for a year. */\n\t| 'immutable'\n\t/** Kept this many seconds. */\n\t| { maxAge: number }\n\t/** Not kept. */\n\t| 'none';\n\n/** What a processor handler returns. */\nexport interface ProcessorResult {\n\tbody: Uint8Array | string;\n\tcontentType: string;\n\t/**\n\t * `immutable` results are also kept in the bucket, so the next request\n\t * for them never runs the handler. Defaults to an hour, kept nowhere.\n\t */\n\tcache?: ProcessorCache;\n}\n\n/**\n * The object a request addresses, read from the bucket on first use.\n *\n * Its body is one GET, made by the first `bytes()` or `stream()`; what is\n * known about it is one HEAD, made by the first `size()` or `metadata()`.\n * Either throws `ProcessorSourceMissing` when the object is not there, which\n * answers the request with a 404.\n */\nexport interface SourceObject {\n\treadonly key: string;\n\t/** Its size in bytes, from a HEAD: the body is not downloaded. */\n\tsize(): Promise<number>;\n\t/** Everything a HEAD answers, without downloading the body. */\n\tmetadata(): Promise<ObjectMetadata>;\n\tbytes(): Promise<Uint8Array>;\n\tstream(): Promise<ReadableStream<Uint8Array>>;\n\t/**\n\t * The type it was stored with: from the body's response when it has\n\t * already been read, otherwise from a HEAD.\n\t */\n\tcontentType(): Promise<string | undefined>;\n}\n\nexport interface ProcessorContext<\n\tTParams,\n\tTServices extends Service[],\n\tTLogger extends Logger,\n> {\n\tparams: TParams;\n\tkey: string;\n\tobject: SourceObject;\n\tlogger: TLogger;\n\tservices: ServiceRecord<TServices>;\n}\n\nexport type ProcessorHandler<\n\tTParams,\n\tTServices extends Service[],\n\tTLogger extends Logger,\n> = (\n\tcontext: ProcessorContext<TParams, TServices, TLogger>,\n) => Promise<ProcessorResult> | ProcessorResult;\n\n/** What a processor's parameters parse to: its schema's output, or the raw strings. */\nexport type ProcessorParams<\n\tTPattern extends string,\n\tTSchema extends StandardSchemaV1 | undefined,\n> = TSchema extends StandardSchemaV1\n\t? InferStandardSchema<TSchema>\n\t: PatternParams<TPattern>;\n\n/**\n * A processor — a handler behind one path pattern of a file server, which\n * makes a derivative of an open object on read: a thumbnail, a page of a PDF.\n *\n * Built from the file server (`assets.process('/i/:width/*')`), so it carries\n * the bucket it reads and the open paths it may serve. Its parameters' schema\n * is the allowlist: a request outside it is refused before anything runs, so\n * nobody can mint new work — or new cache entries — by varying a number.\n */\nexport class Processor<\n\tTPattern extends string = string,\n\tTSchema extends StandardSchemaV1 | undefined = undefined,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n> extends Construct<TLogger, undefined, TServices> {\n\t__IS_PROCESSOR__ = true;\n\n\tstatic isProcessor(obj: unknown): obj is Processor<string, any, any, any> {\n\t\treturn Boolean(\n\t\t\tobj &&\n\t\t\t\t(obj as { __IS_PROCESSOR__?: boolean }).__IS_PROCESSOR__ === true &&\n\t\t\t\t(obj as Construct).type === ConstructType.Processor,\n\t\t);\n\t}\n\n\tconstructor(\n\t\treadonly parsed: ParsedPattern,\n\t\treadonly handler: ProcessorHandler<\n\t\t\tProcessorParams<TPattern, TSchema>,\n\t\t\tTServices,\n\t\t\tTLogger\n\t\t>,\n\t\treadonly options: {\n\t\t\t/** The file server's surface id — the unit that runs it. */\n\t\t\tsurfaceId: string;\n\t\t\t/** The bucket it reads from and keeps derivatives in. */\n\t\t\tbucketId: string;\n\t\t\t/** How it reaches that bucket. */\n\t\t\torigin: Service<string, StorageClient>;\n\t\t\t/** Whether a key is one of the file server's open paths. */\n\t\t\tserves: (key: string) => boolean;\n\t\t\tparamsSchema?: TSchema;\n\t\t\t/** Packages with native code, installed for the target. */\n\t\t\tnative: readonly string[];\n\t\t\tlogger: TLogger;\n\t\t\tservices: TServices;\n\t\t\tconstructs: string[];\n\t\t\ttimeout?: number;\n\t\t\tmemorySize?: number;\n\t\t},\n\t) {\n\t\tsuper(\n\t\t\tConstructType.Processor,\n\t\t\toptions.logger,\n\t\t\t// The bucket is reached like any service — which is also how its URL\n\t\t\t// is found by the environment sniffer.\n\t\t\t[options.origin, ...options.services] as unknown as TServices,\n\t\t\t[],\n\t\t\tundefined,\n\t\t\toptions.timeout,\n\t\t\toptions.memorySize,\n\t\t\tundefined,\n\t\t\t// The bucket is an edge of its process, so the unit running it is\n\t\t\t// handed the bucket's address.\n\t\t\t[...new Set([options.bucketId, ...options.constructs])],\n\t\t);\n\t\tthis.owner = options.surfaceId;\n\t}\n\n\t/** The pattern it answers, as written. */\n\tget pattern(): TPattern {\n\t\treturn this.parsed.pattern as TPattern;\n\t}\n\n\t/** The literal path the edge routes to it — `/i/`. */\n\tget prefix(): string {\n\t\treturn this.parsed.prefix;\n\t}\n\n\tget native(): readonly string[] {\n\t\treturn this.options.native;\n\t}\n\n\tget surfaceId(): string {\n\t\treturn this.options.surfaceId;\n\t}\n\n\tget bucketId(): string {\n\t\treturn this.options.bucketId;\n\t}\n}\n","import type { Logger } from '@geekmidas/logger';\nimport type { Service } from '@geekmidas/services';\nimport type { StorageClient } from '@geekmidas/storage';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport {\n\ttype Consumable,\n\tidsOf,\n\ttype ServicesOf,\n\tservicesOf,\n} from '../construct-interface';\nimport {\n\tProcessor,\n\ttype ProcessorHandler,\n\ttype ProcessorParams,\n} from './Processor';\nimport type { ParsedPattern } from './pattern';\n\n/** A native package named in a way no installer could resolve. */\nexport class ProcessorNativeInvalid extends Error {\n\tconstructor(readonly packageName: string) {\n\t\tsuper(\n\t\t\t`'${packageName}' is not a package name. Name the package with native code ` +\n\t\t\t\t`as it is installed — 'sharp', '@napi-rs/canvas' — and its version ` +\n\t\t\t\t`is taken from the app's package.json.`,\n\t\t);\n\t\tthis.name = 'ProcessorNativeInvalid';\n\t}\n}\n\ninterface ProcessorBuilderState<TLogger extends Logger> {\n\tparsed: ParsedPattern;\n\tsurfaceId: string;\n\tbucketId: string;\n\torigin: Service<string, StorageClient>;\n\tserves: (key: string) => boolean;\n\tlogger: TLogger;\n\tparamsSchema?: StandardSchemaV1;\n\tnative: string[];\n\tservices: Service[];\n\tconstructs: string[];\n\ttimeout?: number;\n\tmemorySize?: number;\n}\n\n/**\n * What `fileServer.process(pattern)` returns: a processor, built up one\n * immutable step at a time and finished by `.handle()`.\n */\nexport class ProcessorBuilder<\n\tTPattern extends string,\n\tTSchema extends StandardSchemaV1 | undefined = undefined,\n\tTServices extends Service[] = [],\n\tTLogger extends Logger = Logger,\n> {\n\tconstructor(private readonly state: ProcessorBuilderState<TLogger>) {}\n\n\t/**\n\t * The parameters' schema — the allowlist. Every request is parsed by it\n\t * before anything runs, and one it refuses is answered 400.\n\t */\n\tparams<T extends StandardSchemaV1>(\n\t\tschema: T,\n\t): ProcessorBuilder<TPattern, T, TServices, TLogger> {\n\t\treturn new ProcessorBuilder({ ...this.state, paramsSchema: schema });\n\t}\n\n\t/** Constructs its handler reaches, as `services.<id>`. */\n\tdependsOn<const T extends readonly Consumable[]>(\n\t\tconstructs: T,\n\t): ProcessorBuilder<\n\t\tTPattern,\n\t\tTSchema,\n\t\t[...TServices, ...ServicesOf<T>],\n\t\tTLogger\n\t> {\n\t\tconst services = servicesOf(constructs) as unknown as Service[];\n\t\treturn new ProcessorBuilder({\n\t\t\t...this.state,\n\t\t\tservices: [\n\t\t\t\t...this.state.services.filter(\n\t\t\t\t\t(service) =>\n\t\t\t\t\t\t!services.some((s) => s.serviceName === service.serviceName),\n\t\t\t\t),\n\t\t\t\t...services,\n\t\t\t],\n\t\t\tconstructs: idsOf(constructs, this.state.constructs),\n\t\t});\n\t}\n\n\t/**\n\t * Packages with native code — `sharp` — installed for the target the\n\t * processor runs on rather than bundled: linux in its image, arm64 on\n\t * Lambda.\n\t */\n\tnative(packages: readonly string[]): this {\n\t\tfor (const name of packages) {\n\t\t\tif (!/^(@[a-z0-9._~-]+\\/)?[a-z0-9._~-]+$/.test(name)) {\n\t\t\t\tthrow new ProcessorNativeInvalid(name);\n\t\t\t}\n\t\t}\n\t\treturn new ProcessorBuilder({\n\t\t\t...this.state,\n\t\t\tnative: [...new Set([...this.state.native, ...packages])],\n\t\t}) as this;\n\t}\n\n\t/** Milliseconds a request may take, where the target bounds it. */\n\ttimeout(ms: number): this {\n\t\treturn new ProcessorBuilder({ ...this.state, timeout: ms }) as this;\n\t}\n\n\t/** Megabytes of memory, where the target sets it. */\n\tmemorySize(mb: number): this {\n\t\treturn new ProcessorBuilder({ ...this.state, memorySize: mb }) as this;\n\t}\n\n\thandle(\n\t\tfn: ProcessorHandler<\n\t\t\tProcessorParams<TPattern, TSchema>,\n\t\t\tTServices,\n\t\t\tTLogger\n\t\t>,\n\t): Processor<TPattern, TSchema, TServices, TLogger> {\n\t\tconst { state } = this;\n\t\treturn new Processor<TPattern, TSchema, TServices, TLogger>(\n\t\t\tstate.parsed,\n\t\t\tfn,\n\t\t\t{\n\t\t\t\tsurfaceId: state.surfaceId,\n\t\t\t\tbucketId: state.bucketId,\n\t\t\t\torigin: state.origin,\n\t\t\t\tserves: state.serves,\n\t\t\t\t...(state.paramsSchema\n\t\t\t\t\t? { paramsSchema: state.paramsSchema as TSchema }\n\t\t\t\t\t: {}),\n\t\t\t\tnative: state.native,\n\t\t\t\tlogger: state.logger,\n\t\t\t\tservices: state.services as TServices,\n\t\t\t\tconstructs: state.constructs,\n\t\t\t\t...(state.timeout !== undefined ? { timeout: state.timeout } : {}),\n\t\t\t\t...(state.memorySize !== undefined\n\t\t\t\t\t? { memorySize: state.memorySize }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t);\n\t}\n}\n","/**\n * A processor's path pattern: literal segments, `:name` parameters, and a\n * final `*` that is the object's key.\n *\n * ```\n * /i/:width/* → /i/256/avatars/7.png { width: '256' }, 'avatars/7.png'\n * /pdf/:page/:dpi/* → /pdf/1/150/doc.pdf { page: '1', dpi: '150' }, 'doc.pdf'\n * ```\n *\n * It starts with a literal segment because the edge routes on that prefix: a\n * pattern beginning with a parameter would claim every path on the file\n * server, objects included.\n */\n\n/** The parameter names a pattern declares, as a union. */\nexport type PatternParamNames<P extends string> =\n\tP extends `${string}/:${infer Name}/${infer Rest}`\n\t\t? Name | PatternParamNames<`/${Rest}`>\n\t\t: never;\n\n/** The raw parameters a pattern matches, before its schema parses them. */\nexport type PatternParams<P extends string> = {\n\t[K in PatternParamNames<P>]: string;\n};\n\n/** A pattern a processor cannot be served on. */\nexport class ProcessorPatternInvalid extends Error {\n\tconstructor(\n\t\treadonly pattern: string,\n\t\treadonly reason: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${pattern}' is not a processor pattern: ${reason}. A pattern is a ` +\n\t\t\t\t`literal first segment, then any \\`:name\\` parameters, then \\`*\\` ` +\n\t\t\t\t`for the object's key — '/i/:width/*'.`,\n\t\t);\n\t\tthis.name = 'ProcessorPatternInvalid';\n\t}\n}\n\n/** A pattern, parsed once. */\nexport interface ParsedPattern {\n\treadonly pattern: string;\n\t/** Each segment before the key: a literal, or a parameter's name. */\n\treadonly segments: readonly (\n\t\t| { kind: 'literal'; value: string }\n\t\t| { kind: 'param'; name: string }\n\t)[];\n\t/** The parameter names, in the order they appear. */\n\treadonly params: readonly string[];\n\t/** The literal path the edge routes on — `/i/`. */\n\treadonly prefix: string;\n}\n\n/** @throws {ProcessorPatternInvalid} */\nexport function parsePattern(pattern: string): ParsedPattern {\n\tif (!pattern.startsWith('/')) {\n\t\tthrow new ProcessorPatternInvalid(pattern, 'it does not start with /');\n\t}\n\tif (!pattern.endsWith('/*')) {\n\t\tthrow new ProcessorPatternInvalid(\n\t\t\tpattern,\n\t\t\t'it does not end with /* — the key',\n\t\t);\n\t}\n\n\tconst parts = pattern.slice(1, -2).split('/');\n\tconst segments: ParsedPattern['segments'][number][] = [];\n\tconst params: string[] = [];\n\tfor (const part of parts) {\n\t\tif (part === '') {\n\t\t\tthrow new ProcessorPatternInvalid(pattern, 'it has an empty segment');\n\t\t}\n\t\tif (part.includes('*')) {\n\t\t\tthrow new ProcessorPatternInvalid(\n\t\t\t\tpattern,\n\t\t\t\t'only its last segment may be *',\n\t\t\t);\n\t\t}\n\t\tif (part.startsWith(':')) {\n\t\t\tconst name = part.slice(1);\n\t\t\tif (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {\n\t\t\t\tthrow new ProcessorPatternInvalid(\n\t\t\t\t\tpattern,\n\t\t\t\t\t`'${part}' is not a parameter name`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (params.includes(name)) {\n\t\t\t\tthrow new ProcessorPatternInvalid(pattern, `'${name}' appears twice`);\n\t\t\t}\n\t\t\tparams.push(name);\n\t\t\tsegments.push({ kind: 'param', name });\n\t\t\tcontinue;\n\t\t}\n\t\tif (!/^[A-Za-z0-9._~-]+$/.test(part)) {\n\t\t\tthrow new ProcessorPatternInvalid(\n\t\t\t\tpattern,\n\t\t\t\t`'${part}' has characters a path segment would escape`,\n\t\t\t);\n\t\t}\n\t\tsegments.push({ kind: 'literal', value: part });\n\t}\n\n\tconst first = segments[0];\n\tif (!first || first.kind !== 'literal') {\n\t\tthrow new ProcessorPatternInvalid(\n\t\t\tpattern,\n\t\t\t'its first segment is a parameter, which would claim every path',\n\t\t);\n\t}\n\n\tconst literals: string[] = [];\n\tfor (const segment of segments) {\n\t\tif (segment.kind !== 'literal') break;\n\t\tliterals.push(segment.value);\n\t}\n\n\treturn { pattern, segments, params, prefix: `/${literals.join('/')}/` };\n}\n\n/** A path the pattern matched: its raw parameters and the key. */\nexport interface PatternMatch {\n\tparams: Record<string, string>;\n\tkey: string;\n}\n\n/**\n * Match a request path, decoding each parameter and each key segment. A path\n * with an empty key, or one that decodes to a `..` segment, matches nothing.\n */\nexport function matchPattern(\n\tparsed: ParsedPattern,\n\tpath: string,\n): PatternMatch | undefined {\n\tconst parts = path.replace(/^\\/+/, '').split('/');\n\tif (parts.length <= parsed.segments.length) return undefined;\n\n\tconst params: Record<string, string> = {};\n\tfor (const [index, segment] of parsed.segments.entries()) {\n\t\tconst part = decode(parts[index] ?? '');\n\t\tif (part === undefined || part === '') return undefined;\n\t\tif (segment.kind === 'literal') {\n\t\t\tif (part !== segment.value) return undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tparams[segment.name] = part;\n\t}\n\n\tconst keyParts = parts.slice(parsed.segments.length).map(decode);\n\tif (keyParts.some((part) => part === undefined || part === '..')) {\n\t\treturn undefined;\n\t}\n\tconst key = keyParts.join('/');\n\tif (key === '' || keyParts.includes('')) return undefined;\n\n\treturn { params, key };\n}\n\n/** The path that addresses `key` through the pattern with these parameters. */\nexport function fillPattern(\n\tparsed: ParsedPattern,\n\tparams: Readonly<Record<string, string | number>>,\n\tkey: string,\n): string {\n\tconst head = parsed.segments.map((segment) => {\n\t\tif (segment.kind === 'literal') return segment.value;\n\t\tconst value = params[segment.name];\n\t\tif (value === undefined || `${value}` === '') {\n\t\t\tthrow new ProcessorParamMissing(parsed.pattern, segment.name);\n\t\t}\n\t\treturn encodeURIComponent(`${value}`);\n\t});\n\tconst tail = key\n\t\t.replace(/^\\/+/, '')\n\t\t.split('/')\n\t\t.map((part) => encodeURIComponent(part));\n\n\treturn `/${[...head, ...tail].join('/')}`;\n}\n\n/** A processed URL was asked for without one of the pattern's parameters. */\nexport class ProcessorParamMissing extends Error {\n\tconstructor(\n\t\treadonly pattern: string,\n\t\treadonly param: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${pattern}' needs '${param}' to address an object, and it was not given.`,\n\t\t);\n\t\tthis.name = 'ProcessorParamMissing';\n\t}\n}\n\nfunction decode(part: string): string | undefined {\n\ttry {\n\t\treturn decodeURIComponent(part);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;AAiGA,IAAa,YAAb,cAKUA,kBAAAA,UAAyC;CAYxC;CACA;CAKA;CAjBV,mBAAmB;CAEnB,OAAO,YAAY,KAAuD;EACzE,OAAO,QACN,OACE,IAAuC,qBAAqB,QAC5D,IAAkB,SAAA,kCACrB;CACD;CAEA,YACC,QACA,SAKA,SAkBC;EACD,MAAA,oCAEC,QAAQ,QAGR,CAAC,QAAQ,QAAQ,GAAG,QAAQ,QAAQ,GACpC,CAAC,GACD,KAAA,GACA,QAAQ,SACR,QAAQ,YACR,KAAA,GAGA,CAAC,mBAAG,IAAI,IAAI,CAAC,QAAQ,UAAU,GAAG,QAAQ,UAAU,CAAC,CAAC,CACvD;EAvCS,KAAA,SAAA;EACA,KAAA,UAAA;EAKA,KAAA,UAAA;EAkCT,KAAK,QAAQ,QAAQ;CACtB;;CAGA,IAAI,UAAoB;EACvB,OAAO,KAAK,OAAO;CACpB;;CAGA,IAAI,SAAiB;EACpB,OAAO,KAAK,OAAO;CACpB;CAEA,IAAI,SAA4B;EAC/B,OAAO,KAAK,QAAQ;CACrB;CAEA,IAAI,YAAoB;EACvB,OAAO,KAAK,QAAQ;CACrB;CAEA,IAAI,WAAmB;EACtB,OAAO,KAAK,QAAQ;CACrB;AACD;;;;AChKA,IAAa,yBAAb,cAA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ACf,QACA,QACA,KACS;CACT,MAAM,OAAO,OAAO,SAAS,KAAK,YAAY;EAC7C,IAAI,QAAQ,SAAS,WAAW,OAAO,QAAQ;EAC/C,MAAM,QAAQ,OAAO,QAAQ;EAC7B,IAAI,UAAU,KAAA,KAAa,GAAG,YAAY,IACzC,MAAM,IAAI,sBAAsB,OAAO,SAAS,QAAQ,IAAI;EAE7D,OAAO,mBAAmB,GAAG,OAAO;CACrC,CAAC;CACD,MAAM,OAAO,IACX,QAAQ,QAAQ,EAAE,CAAC,CACnB,MAAM,GAAG,CAAC,CACV,KAAK,SAAS,mBAAmB,IAAI,CAAC;CAExC,OAAO,IAAI,CAAC,GAAG,MAAM,GAAG,IAAI,CAAC,CAAC,KAAK,GAAG;AACvC;;AAGA,IAAa,wBAAb,cAA2C,MAAM;CAEtC;CACA;CAFV,YACC,SACA,OACC;EACD,MACC,IAAI,QAAQ,WAAW,MAAM,8CAC9B;EALS,KAAA,UAAA;EACA,KAAA,QAAA;EAKT,KAAK,OAAO;CACb;AACD;AAEA,SAAS,OAAO,MAAkC;CACjD,IAAI;EACH,OAAO,mBAAmB,IAAI;CAC/B,QAAQ;EACP;CACD;AACD"}
@@ -91,15 +91,25 @@ async function run(processor, match, options) {
91
91
  source = found.response;
92
92
  return source;
93
93
  };
94
+ let head;
95
+ const metadata = () => {
96
+ head ??= storage.head(key).then((found) => {
97
+ if (!found) throw new ProcessorSourceMissing(key);
98
+ return found;
99
+ });
100
+ return head;
101
+ };
94
102
  const object = {
95
103
  key,
104
+ size: async () => (await metadata()).size,
105
+ metadata,
96
106
  bytes: async () => new Uint8Array(await (await load()).arrayBuffer()),
97
107
  stream: async () => {
98
108
  const body = (await load()).body;
99
109
  if (!body) throw new ProcessorSourceMissing(key);
100
110
  return body;
101
111
  },
102
- contentType: async () => (await load()).headers.get("content-type") ?? void 0
112
+ contentType: async () => source ? source.headers.get("content-type") ?? void 0 : (await metadata()).contentType
103
113
  };
104
114
  let result;
105
115
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["DERIVED_PREFIX","fillPattern","matchPattern","runWithRequestContext","defaultEnvParser","ServiceDiscovery","defaultEnvParser"],"sources":["../../src/processors/runProcessor.ts","../../src/processors/AWSLambdaProcessor.ts"],"sourcesContent":["import type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { runWithRequestContext, ServiceDiscovery } from '@geekmidas/services';\nimport type { StorageClient } from '@geekmidas/storage';\nimport { defaultEnvParser } from '../endpoints/surfaceEnv';\nimport {\n\tDERIVED_PREFIX,\n\ttype Processor,\n\ttype ProcessorCache,\n\ttype SourceObject,\n} from './Processor';\nimport { fillPattern, matchPattern } from './pattern';\n\n/** What a processor answers, for whichever server or function carries it. */\nexport interface ProcessorResponse {\n\tstatus: number;\n\theaders: Record<string, string>;\n\tbody?: Uint8Array | string;\n}\n\n/** The object a request addressed is not in the bucket. */\nexport class ProcessorSourceMissing extends Error {\n\tconstructor(readonly key: string) {\n\t\tsuper(`'${key}' is not in the bucket, so there is nothing to process.`);\n\t\tthis.name = 'ProcessorSourceMissing';\n\t}\n}\n\n/** What a refusal or a miss may be kept for: long enough to absorb a burst. */\nconst SHORT = 'public, max-age=60';\n\n/** The header a response carries, by how long it may be kept. */\nexport function cacheControl(cache: ProcessorCache | undefined): string {\n\tif (cache === 'immutable') return 'public, max-age=31536000, immutable';\n\tif (cache === 'none') return 'no-store';\n\treturn `public, max-age=${cache?.maxAge ?? 3600}`;\n}\n\n/** Where a processor keeps the derivative for one request. */\nexport function derivedKey(\n\tprocessor: Processor<string, any, any, any>,\n\tparams: Readonly<Record<string, string>>,\n\tkey: string,\n): string {\n\treturn `${DERIVED_PREFIX}${fillPattern(processor.parsed, params, key).slice(1)}`;\n}\n\nexport interface ProcessorRequestOptions {\n\tserviceDiscovery: ServiceDiscovery<any>;\n\t/** How the bucket is read through a presigned address. */\n\tfetch?: typeof fetch;\n}\n\n/**\n * Answer one request with the first processor whose pattern matches it, or\n * `undefined` when none does.\n *\n * In order: the parameters are parsed by the processor's schema (400 when it\n * refuses them); the key must be one of the file server's open paths (404\n * otherwise, as an unsigned read of it would be); a derivative already in the\n * bucket is answered without running anything; and only then is the handler\n * run, its `immutable` result written through for next time.\n */\nexport async function handleProcessorRequest(\n\tprocessors: readonly Processor<string, any, any, any>[],\n\trequest: { method: string; path: string },\n\toptions: ProcessorRequestOptions,\n): Promise<ProcessorResponse | undefined> {\n\tconst method = request.method.toUpperCase();\n\n\tfor (const processor of processors) {\n\t\tconst match = matchPattern(processor.parsed, request.path);\n\t\tif (!match) continue;\n\n\t\tif (method !== 'GET' && method !== 'HEAD') {\n\t\t\treturn text(405, 'Method Not Allowed', 'no-store', {\n\t\t\t\tallow: 'GET, HEAD',\n\t\t\t});\n\t\t}\n\n\t\treturn runWithRequestContext(\n\t\t\t{\n\t\t\t\tlogger: processor.logger,\n\t\t\t\trequestId: `processor-${Date.now()}`,\n\t\t\t\tstartTime: Date.now(),\n\t\t\t\toperation: `processor ${processor.pattern}`,\n\t\t\t},\n\t\t\t() => run(processor, match, options),\n\t\t);\n\t}\n\n\treturn undefined;\n}\n\n/**\n * A request handler for a set of processors — what a generated entry serves\n * — with its services discovered from the default environment parser: the\n * process's environment and the credentials `gkm` injected.\n */\nexport function processorServer(\n\tprocessors: readonly Processor<string, any, any, any>[],\n\tenvParser: EnvironmentParser<{}> = defaultEnvParser(),\n): (request: {\n\tmethod: string;\n\tpath: string;\n}) => Promise<ProcessorResponse | undefined> {\n\tconst serviceDiscovery = ServiceDiscovery.getInstance(envParser);\n\treturn (request) =>\n\t\thandleProcessorRequest(processors, request, { serviceDiscovery });\n}\n\nasync function run(\n\tprocessor: Processor<string, any, any, any>,\n\tmatch: { params: Record<string, string>; key: string },\n\toptions: ProcessorRequestOptions,\n): Promise<ProcessorResponse> {\n\tconst logger = processor.logger as Logger;\n\tconst fetcher = options.fetch ?? fetch;\n\tconst { key } = match;\n\n\tconst schema = processor.options.paramsSchema;\n\tlet params: unknown = match.params;\n\tif (schema) {\n\t\tconst parsed = await schema['~standard'].validate(match.params);\n\t\tif (parsed.issues) return text(400, 'Bad Request', SHORT);\n\t\tparams = parsed.value;\n\t}\n\n\t// A derivative is never itself a source, and a private object is never\n\t// processed: a processor serves exactly what an unsigned read would.\n\tif (key.startsWith(DERIVED_PREFIX) || !processor.options.serves(key)) {\n\t\treturn text(404, 'Not Found', SHORT);\n\t}\n\n\tconst services: Record<string, unknown> =\n\t\tawait options.serviceDiscovery.register(processor.services);\n\tconst storage = services[\n\t\tprocessor.options.origin.serviceName\n\t] as StorageClient;\n\n\tconst derived = derivedKey(processor, match.params, key);\n\tconst kept = await read(storage, derived, fetcher);\n\tif (kept) {\n\t\treturn {\n\t\t\tstatus: 200,\n\t\t\theaders: {\n\t\t\t\t'content-type': kept.contentType ?? 'application/octet-stream',\n\t\t\t\t'cache-control': cacheControl('immutable'),\n\t\t\t\t'x-gkm-processor': 'kept',\n\t\t\t},\n\t\t\tbody: new Uint8Array(await kept.response.arrayBuffer()),\n\t\t};\n\t}\n\n\tlet source: Response | undefined;\n\tconst load = async (): Promise<Response> => {\n\t\tif (source) return source;\n\t\tconst found = await read(storage, key, fetcher);\n\t\tif (!found) throw new ProcessorSourceMissing(key);\n\t\tsource = found.response;\n\t\treturn source;\n\t};\n\tconst object: SourceObject = {\n\t\tkey,\n\t\tbytes: async () => new Uint8Array(await (await load()).arrayBuffer()),\n\t\tstream: async () => {\n\t\t\tconst body = (await load()).body;\n\t\t\tif (!body) throw new ProcessorSourceMissing(key);\n\t\t\treturn body;\n\t\t},\n\t\tcontentType: async () =>\n\t\t\t(await load()).headers.get('content-type') ?? undefined,\n\t};\n\n\tlet result: Awaited<ReturnType<typeof processor.handler>>;\n\ttry {\n\t\tresult = await processor.handler({\n\t\t\tparams,\n\t\t\tkey,\n\t\t\tobject,\n\t\t\tlogger,\n\t\t\tservices,\n\t\t} as never);\n\t} catch (error) {\n\t\tif (error instanceof ProcessorSourceMissing) {\n\t\t\treturn text(404, 'Not Found', SHORT);\n\t\t}\n\t\tlogger.error({ err: error, key }, 'Processor failed');\n\t\treturn text(500, 'Internal Server Error', 'no-store');\n\t}\n\n\tconst body =\n\t\ttypeof result.body === 'string'\n\t\t\t? new TextEncoder().encode(result.body)\n\t\t\t: result.body;\n\n\t// Kept only when it can never change: anything else would be served from\n\t// the bucket long after its handler would have answered differently.\n\tif (result.cache === 'immutable') {\n\t\tawait storage\n\t\t\t.upload(derived, Buffer.from(body), result.contentType)\n\t\t\t.catch((error: unknown) =>\n\t\t\t\tlogger.warn({ err: error, key: derived }, 'Could not keep derivative'),\n\t\t\t);\n\t}\n\n\treturn {\n\t\tstatus: 200,\n\t\theaders: {\n\t\t\t'content-type': result.contentType,\n\t\t\t'cache-control': cacheControl(result.cache),\n\t\t\t'x-gkm-processor': 'made',\n\t\t},\n\t\tbody,\n\t};\n}\n\n/** An object through a presigned address, or nothing when it is not there. */\nasync function read(\n\tstorage: StorageClient,\n\tkey: string,\n\tfetcher: typeof fetch,\n): Promise<{ response: Response; contentType?: string } | undefined> {\n\tconst url = await storage.getDownloadURL({ path: key });\n\tconst response = await fetcher(url);\n\tif (!response.ok) {\n\t\tawait response.body?.cancel().catch(() => undefined);\n\t\treturn undefined;\n\t}\n\tconst contentType = response.headers.get('content-type') ?? undefined;\n\treturn { response, ...(contentType ? { contentType } : {}) };\n}\n\nfunction text(\n\tstatus: number,\n\tbody: string,\n\tcache: string,\n\textra: Record<string, string> = {},\n): ProcessorResponse {\n\treturn {\n\t\tstatus,\n\t\theaders: {\n\t\t\t'content-type': 'text/plain; charset=utf-8',\n\t\t\t'cache-control': cache,\n\t\t\t...extra,\n\t\t},\n\t\tbody,\n\t};\n}\n","import type { EnvironmentParser } from '@geekmidas/envkit';\nimport { defaultEnvParser } from '../endpoints/surfaceEnv';\nimport type { Processor } from './Processor';\nimport { processorServer } from './runProcessor';\n\n/** The parts of a Lambda function URL event a processor reads. */\nexport interface FunctionUrlEvent {\n\trawPath: string;\n\trequestContext: { http: { method: string } };\n}\n\n/** What a function URL answers with. */\nexport interface FunctionUrlResult {\n\tstatusCode: number;\n\theaders: Record<string, string>;\n\tbody: string;\n\tisBase64Encoded: boolean;\n}\n\n/**\n * A processor as a Lambda behind a function URL — the CDN's origin for its\n * pattern on AWS. The URL takes IAM auth and the CDN signs each request, so\n * the function cannot be called around the cache.\n */\nexport class AWSLambdaProcessor {\n\tprivate readonly serve: ReturnType<typeof processorServer>;\n\n\tconstructor(\n\t\tprocessor: Processor<string, any, any, any>,\n\t\tenvParser: EnvironmentParser<{}> = defaultEnvParser(),\n\t) {\n\t\tthis.serve = processorServer([processor], envParser);\n\t}\n\n\thandler = async (event: FunctionUrlEvent): Promise<FunctionUrlResult> => {\n\t\tconst response = await this.serve({\n\t\t\tmethod: event.requestContext.http.method,\n\t\t\tpath: event.rawPath,\n\t\t});\n\t\tif (!response) {\n\t\t\treturn {\n\t\t\t\tstatusCode: 404,\n\t\t\t\theaders: { 'cache-control': 'public, max-age=60' },\n\t\t\t\tbody: '',\n\t\t\t\tisBase64Encoded: false,\n\t\t\t};\n\t\t}\n\t\tconst body = response.body ?? '';\n\t\treturn {\n\t\t\tstatusCode: response.status,\n\t\t\theaders: response.headers,\n\t\t\tbody:\n\t\t\t\ttypeof body === 'string' ? body : Buffer.from(body).toString('base64'),\n\t\t\tisBase64Encoded: typeof body !== 'string',\n\t\t};\n\t};\n}\n"],"mappings":";;;;;;;AAqBA,IAAa,yBAAb,cAA4C,MAAM;CAC5B;CAArB,YAAY,KAAsB;EACjC,MAAM,IAAI,IAAI,wDAAwD;EADlD,KAAA,MAAA;EAEpB,KAAK,OAAO;CACb;AACD;;AAGA,MAAM,QAAQ;;AAGd,SAAgB,aAAa,OAA2C;CACvE,IAAI,UAAU,aAAa,OAAO;CAClC,IAAI,UAAU,QAAQ,OAAO;CAC7B,OAAO,mBAAmB,OAAO,UAAU;AAC5C;;AAGA,SAAgB,WACf,WACA,QACA,KACS;CACT,OAAO,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O,SAAS,WAAW,OAAO,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS,QAAQ;GACtE,iBAAiB,OAAO,SAAS;EAClC;CACD;AACD"}
1
+ {"version":3,"file":"index.cjs","names":["DERIVED_PREFIX","fillPattern","matchPattern","runWithRequestContext","defaultEnvParser","ServiceDiscovery","defaultEnvParser"],"sources":["../../src/processors/runProcessor.ts","../../src/processors/AWSLambdaProcessor.ts"],"sourcesContent":["import type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { runWithRequestContext, ServiceDiscovery } from '@geekmidas/services';\nimport type { ObjectMetadata, StorageClient } from '@geekmidas/storage';\nimport { defaultEnvParser } from '../endpoints/surfaceEnv';\nimport {\n\tDERIVED_PREFIX,\n\ttype Processor,\n\ttype ProcessorCache,\n\ttype SourceObject,\n} from './Processor';\nimport { fillPattern, matchPattern } from './pattern';\n\n/** What a processor answers, for whichever server or function carries it. */\nexport interface ProcessorResponse {\n\tstatus: number;\n\theaders: Record<string, string>;\n\tbody?: Uint8Array | string;\n}\n\n/** The object a request addressed is not in the bucket. */\nexport class ProcessorSourceMissing extends Error {\n\tconstructor(readonly key: string) {\n\t\tsuper(`'${key}' is not in the bucket, so there is nothing to process.`);\n\t\tthis.name = 'ProcessorSourceMissing';\n\t}\n}\n\n/** What a refusal or a miss may be kept for: long enough to absorb a burst. */\nconst SHORT = 'public, max-age=60';\n\n/** The header a response carries, by how long it may be kept. */\nexport function cacheControl(cache: ProcessorCache | undefined): string {\n\tif (cache === 'immutable') return 'public, max-age=31536000, immutable';\n\tif (cache === 'none') return 'no-store';\n\treturn `public, max-age=${cache?.maxAge ?? 3600}`;\n}\n\n/** Where a processor keeps the derivative for one request. */\nexport function derivedKey(\n\tprocessor: Processor<string, any, any, any>,\n\tparams: Readonly<Record<string, string>>,\n\tkey: string,\n): string {\n\treturn `${DERIVED_PREFIX}${fillPattern(processor.parsed, params, key).slice(1)}`;\n}\n\nexport interface ProcessorRequestOptions {\n\tserviceDiscovery: ServiceDiscovery<any>;\n\t/** How the bucket is read through a presigned address. */\n\tfetch?: typeof fetch;\n}\n\n/**\n * Answer one request with the first processor whose pattern matches it, or\n * `undefined` when none does.\n *\n * In order: the parameters are parsed by the processor's schema (400 when it\n * refuses them); the key must be one of the file server's open paths (404\n * otherwise, as an unsigned read of it would be); a derivative already in the\n * bucket is answered without running anything; and only then is the handler\n * run, its `immutable` result written through for next time.\n */\nexport async function handleProcessorRequest(\n\tprocessors: readonly Processor<string, any, any, any>[],\n\trequest: { method: string; path: string },\n\toptions: ProcessorRequestOptions,\n): Promise<ProcessorResponse | undefined> {\n\tconst method = request.method.toUpperCase();\n\n\tfor (const processor of processors) {\n\t\tconst match = matchPattern(processor.parsed, request.path);\n\t\tif (!match) continue;\n\n\t\tif (method !== 'GET' && method !== 'HEAD') {\n\t\t\treturn text(405, 'Method Not Allowed', 'no-store', {\n\t\t\t\tallow: 'GET, HEAD',\n\t\t\t});\n\t\t}\n\n\t\treturn runWithRequestContext(\n\t\t\t{\n\t\t\t\tlogger: processor.logger,\n\t\t\t\trequestId: `processor-${Date.now()}`,\n\t\t\t\tstartTime: Date.now(),\n\t\t\t\toperation: `processor ${processor.pattern}`,\n\t\t\t},\n\t\t\t() => run(processor, match, options),\n\t\t);\n\t}\n\n\treturn undefined;\n}\n\n/**\n * A request handler for a set of processors — what a generated entry serves\n * — with its services discovered from the default environment parser: the\n * process's environment and the credentials `gkm` injected.\n */\nexport function processorServer(\n\tprocessors: readonly Processor<string, any, any, any>[],\n\tenvParser: EnvironmentParser<{}> = defaultEnvParser(),\n): (request: {\n\tmethod: string;\n\tpath: string;\n}) => Promise<ProcessorResponse | undefined> {\n\tconst serviceDiscovery = ServiceDiscovery.getInstance(envParser);\n\treturn (request) =>\n\t\thandleProcessorRequest(processors, request, { serviceDiscovery });\n}\n\nasync function run(\n\tprocessor: Processor<string, any, any, any>,\n\tmatch: { params: Record<string, string>; key: string },\n\toptions: ProcessorRequestOptions,\n): Promise<ProcessorResponse> {\n\tconst logger = processor.logger as Logger;\n\tconst fetcher = options.fetch ?? fetch;\n\tconst { key } = match;\n\n\tconst schema = processor.options.paramsSchema;\n\tlet params: unknown = match.params;\n\tif (schema) {\n\t\tconst parsed = await schema['~standard'].validate(match.params);\n\t\tif (parsed.issues) return text(400, 'Bad Request', SHORT);\n\t\tparams = parsed.value;\n\t}\n\n\t// A derivative is never itself a source, and a private object is never\n\t// processed: a processor serves exactly what an unsigned read would.\n\tif (key.startsWith(DERIVED_PREFIX) || !processor.options.serves(key)) {\n\t\treturn text(404, 'Not Found', SHORT);\n\t}\n\n\tconst services: Record<string, unknown> =\n\t\tawait options.serviceDiscovery.register(processor.services);\n\tconst storage = services[\n\t\tprocessor.options.origin.serviceName\n\t] as StorageClient;\n\n\tconst derived = derivedKey(processor, match.params, key);\n\tconst kept = await read(storage, derived, fetcher);\n\tif (kept) {\n\t\treturn {\n\t\t\tstatus: 200,\n\t\t\theaders: {\n\t\t\t\t'content-type': kept.contentType ?? 'application/octet-stream',\n\t\t\t\t'cache-control': cacheControl('immutable'),\n\t\t\t\t'x-gkm-processor': 'kept',\n\t\t\t},\n\t\t\tbody: new Uint8Array(await kept.response.arrayBuffer()),\n\t\t};\n\t}\n\n\tlet source: Response | undefined;\n\tconst load = async (): Promise<Response> => {\n\t\tif (source) return source;\n\t\tconst found = await read(storage, key, fetcher);\n\t\tif (!found) throw new ProcessorSourceMissing(key);\n\t\tsource = found.response;\n\t\treturn source;\n\t};\n\t// One HEAD, shared by everything that asks about the object rather than\n\t// for it — a size guard never downloads what it is guarding against.\n\tlet head: Promise<ObjectMetadata> | undefined;\n\tconst metadata = (): Promise<ObjectMetadata> => {\n\t\thead ??= storage.head(key).then((found) => {\n\t\t\tif (!found) throw new ProcessorSourceMissing(key);\n\t\t\treturn found;\n\t\t});\n\t\treturn head;\n\t};\n\tconst object: SourceObject = {\n\t\tkey,\n\t\tsize: async () => (await metadata()).size,\n\t\tmetadata,\n\t\tbytes: async () => new Uint8Array(await (await load()).arrayBuffer()),\n\t\tstream: async () => {\n\t\t\tconst body = (await load()).body;\n\t\t\tif (!body) throw new ProcessorSourceMissing(key);\n\t\t\treturn body;\n\t\t},\n\t\tcontentType: async () =>\n\t\t\tsource\n\t\t\t\t? (source.headers.get('content-type') ?? undefined)\n\t\t\t\t: (await metadata()).contentType,\n\t};\n\n\tlet result: Awaited<ReturnType<typeof processor.handler>>;\n\ttry {\n\t\tresult = await processor.handler({\n\t\t\tparams,\n\t\t\tkey,\n\t\t\tobject,\n\t\t\tlogger,\n\t\t\tservices,\n\t\t} as never);\n\t} catch (error) {\n\t\tif (error instanceof ProcessorSourceMissing) {\n\t\t\treturn text(404, 'Not Found', SHORT);\n\t\t}\n\t\tlogger.error({ err: error, key }, 'Processor failed');\n\t\treturn text(500, 'Internal Server Error', 'no-store');\n\t}\n\n\tconst body =\n\t\ttypeof result.body === 'string'\n\t\t\t? new TextEncoder().encode(result.body)\n\t\t\t: result.body;\n\n\t// Kept only when it can never change: anything else would be served from\n\t// the bucket long after its handler would have answered differently.\n\tif (result.cache === 'immutable') {\n\t\tawait storage\n\t\t\t.upload(derived, Buffer.from(body), result.contentType)\n\t\t\t.catch((error: unknown) =>\n\t\t\t\tlogger.warn({ err: error, key: derived }, 'Could not keep derivative'),\n\t\t\t);\n\t}\n\n\treturn {\n\t\tstatus: 200,\n\t\theaders: {\n\t\t\t'content-type': result.contentType,\n\t\t\t'cache-control': cacheControl(result.cache),\n\t\t\t'x-gkm-processor': 'made',\n\t\t},\n\t\tbody,\n\t};\n}\n\n/** An object through a presigned address, or nothing when it is not there. */\nasync function read(\n\tstorage: StorageClient,\n\tkey: string,\n\tfetcher: typeof fetch,\n): Promise<{ response: Response; contentType?: string } | undefined> {\n\tconst url = await storage.getDownloadURL({ path: key });\n\tconst response = await fetcher(url);\n\tif (!response.ok) {\n\t\tawait response.body?.cancel().catch(() => undefined);\n\t\treturn undefined;\n\t}\n\tconst contentType = response.headers.get('content-type') ?? undefined;\n\treturn { response, ...(contentType ? { contentType } : {}) };\n}\n\nfunction text(\n\tstatus: number,\n\tbody: string,\n\tcache: string,\n\textra: Record<string, string> = {},\n): ProcessorResponse {\n\treturn {\n\t\tstatus,\n\t\theaders: {\n\t\t\t'content-type': 'text/plain; charset=utf-8',\n\t\t\t'cache-control': cache,\n\t\t\t...extra,\n\t\t},\n\t\tbody,\n\t};\n}\n","import type { EnvironmentParser } from '@geekmidas/envkit';\nimport { defaultEnvParser } from '../endpoints/surfaceEnv';\nimport type { Processor } from './Processor';\nimport { processorServer } from './runProcessor';\n\n/** The parts of a Lambda function URL event a processor reads. */\nexport interface FunctionUrlEvent {\n\trawPath: string;\n\trequestContext: { http: { method: string } };\n}\n\n/** What a function URL answers with. */\nexport interface FunctionUrlResult {\n\tstatusCode: number;\n\theaders: Record<string, string>;\n\tbody: string;\n\tisBase64Encoded: boolean;\n}\n\n/**\n * A processor as a Lambda behind a function URL — the CDN's origin for its\n * pattern on AWS. The URL takes IAM auth and the CDN signs each request, so\n * the function cannot be called around the cache.\n */\nexport class AWSLambdaProcessor {\n\tprivate readonly serve: ReturnType<typeof processorServer>;\n\n\tconstructor(\n\t\tprocessor: Processor<string, any, any, any>,\n\t\tenvParser: EnvironmentParser<{}> = defaultEnvParser(),\n\t) {\n\t\tthis.serve = processorServer([processor], envParser);\n\t}\n\n\thandler = async (event: FunctionUrlEvent): Promise<FunctionUrlResult> => {\n\t\tconst response = await this.serve({\n\t\t\tmethod: event.requestContext.http.method,\n\t\t\tpath: event.rawPath,\n\t\t});\n\t\tif (!response) {\n\t\t\treturn {\n\t\t\t\tstatusCode: 404,\n\t\t\t\theaders: { 'cache-control': 'public, max-age=60' },\n\t\t\t\tbody: '',\n\t\t\t\tisBase64Encoded: false,\n\t\t\t};\n\t\t}\n\t\tconst body = response.body ?? '';\n\t\treturn {\n\t\t\tstatusCode: response.status,\n\t\t\theaders: response.headers,\n\t\t\tbody:\n\t\t\t\ttypeof body === 'string' ? body : Buff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EAAE;EAAU,GAAI,cAAc,EAAE,YAAY,IAAI,CAAC;CAAG;AAC5D;AAEA,SAAS,KACR,QACA,MACA,OACA,QAAgC,CAAC,GACb;CACpB,OAAO;EACN;EACA,SAAS;GACR,gBAAgB;GAChB,iBAAiB;GACjB,GAAG;EACJ;EACA;CACD;AACD;;;;;;;;AC9OA,IAAa,qBAAb,MAAgC;CAC/B;CAEA,YACC,WACA,YAAmCM,mBAAAA,iBAAiB,GACnD;EACD,KAAK,QAAQ,gBAAgB,CAAC,SAAS,GAAG,SAAS;CACpD;CAEA,UAAU,OAAO,UAAwD;EACxE,MAAM,WAAW,MAAM,KAAK,MAAM;GACjC,QAAQ,MAAM,eAAe,KAAK;GAClC,MAAM,MAAM;EACb,CAAC;EACD,IAAI,CAAC,UACJ,OAAO;GACN,YAAY;GACZ,SAAS,EAAE,iBAAiB,qBAAqB;GACjD,MAAM;GACN,iBAAiB;EAClB;EAED,MAAM,OAAO,SAAS,QAAQ;EAC9B,OAAO;GACN,YAAY,SAAS;GACrB,SAAS,SAAS;GAClB,MACC,OAAO,SAAS,WAAW,OAAO,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS,QAAQ;GACtE,iBAAiB,OAAO,SAAS;EAClC;CACD;AACD"}
@@ -1,4 +1,4 @@
1
- import { _ as parsePattern, a as ProcessorCache, c as ProcessorParams, d as ParsedPattern, f as PatternParams, g as matchPattern, h as fillPattern, i as Processor, l as ProcessorResult, m as ProcessorPatternInvalid, n as ProcessorNativeInvalid, o as ProcessorContext, p as ProcessorParamMissing, r as DERIVED_PREFIX, s as ProcessorHandler, t as ProcessorBuilder, u as SourceObject } from "../ProcessorBuilder-ClD7tmEe.cjs";
1
+ import { _ as parsePattern, a as ProcessorCache, c as ProcessorParams, d as ParsedPattern, f as PatternParams, g as matchPattern, h as fillPattern, i as Processor, l as ProcessorResult, m as ProcessorPatternInvalid, n as ProcessorNativeInvalid, o as ProcessorContext, p as ProcessorParamMissing, r as DERIVED_PREFIX, s as ProcessorHandler, t as ProcessorBuilder, u as SourceObject } from "../ProcessorBuilder-DLUxw6op.cjs";
2
2
  import { EnvironmentParser } from "@geekmidas/envkit";
3
3
  import { ServiceDiscovery } from "@geekmidas/services";
4
4
  //#region src/processors/AWSLambdaProcessor.d.ts
@@ -1,4 +1,4 @@
1
- import { _ as parsePattern, a as ProcessorCache, c as ProcessorParams, d as ParsedPattern, f as PatternParams, g as matchPattern, h as fillPattern, i as Processor, l as ProcessorResult, m as ProcessorPatternInvalid, n as ProcessorNativeInvalid, o as ProcessorContext, p as ProcessorParamMissing, r as DERIVED_PREFIX, s as ProcessorHandler, t as ProcessorBuilder, u as SourceObject } from "../ProcessorBuilder-CdLwJK4k.mjs";
1
+ import { _ as parsePattern, a as ProcessorCache, c as ProcessorParams, d as ParsedPattern, f as PatternParams, g as matchPattern, h as fillPattern, i as Processor, l as ProcessorResult, m as ProcessorPatternInvalid, n as ProcessorNativeInvalid, o as ProcessorContext, p as ProcessorParamMissing, r as DERIVED_PREFIX, s as ProcessorHandler, t as ProcessorBuilder, u as SourceObject } from "../ProcessorBuilder-CekwYHGD.mjs";
2
2
  import { ServiceDiscovery } from "@geekmidas/services";
3
3
  import { EnvironmentParser } from "@geekmidas/envkit";
4
4
  //#region src/processors/AWSLambdaProcessor.d.ts
@@ -89,15 +89,25 @@ async function run(processor, match, options) {
89
89
  source = found.response;
90
90
  return source;
91
91
  };
92
+ let head;
93
+ const metadata = () => {
94
+ head ??= storage.head(key).then((found) => {
95
+ if (!found) throw new ProcessorSourceMissing(key);
96
+ return found;
97
+ });
98
+ return head;
99
+ };
92
100
  const object = {
93
101
  key,
102
+ size: async () => (await metadata()).size,
103
+ metadata,
94
104
  bytes: async () => new Uint8Array(await (await load()).arrayBuffer()),
95
105
  stream: async () => {
96
106
  const body = (await load()).body;
97
107
  if (!body) throw new ProcessorSourceMissing(key);
98
108
  return body;
99
109
  },
100
- contentType: async () => (await load()).headers.get("content-type") ?? void 0
110
+ contentType: async () => source ? source.headers.get("content-type") ?? void 0 : (await metadata()).contentType
101
111
  };
102
112
  let result;
103
113
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/processors/runProcessor.ts","../../src/processors/AWSLambdaProcessor.ts"],"sourcesContent":["import type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { runWithRequestContext, ServiceDiscovery } from '@geekmidas/services';\nimport type { StorageClient } from '@geekmidas/storage';\nimport { defaultEnvParser } from '../endpoints/surfaceEnv';\nimport {\n\tDERIVED_PREFIX,\n\ttype Processor,\n\ttype ProcessorCache,\n\ttype SourceObject,\n} from './Processor';\nimport { fillPattern, matchPattern } from './pattern';\n\n/** What a processor answers, for whichever server or function carries it. */\nexport interface ProcessorResponse {\n\tstatus: number;\n\theaders: Record<string, string>;\n\tbody?: Uint8Array | string;\n}\n\n/** The object a request addressed is not in the bucket. */\nexport class ProcessorSourceMissing extends Error {\n\tconstructor(readonly key: string) {\n\t\tsuper(`'${key}' is not in the bucket, so there is nothing to process.`);\n\t\tthis.name = 'ProcessorSourceMissing';\n\t}\n}\n\n/** What a refusal or a miss may be kept for: long enough to absorb a burst. */\nconst SHORT = 'public, max-age=60';\n\n/** The header a response carries, by how long it may be kept. */\nexport function cacheControl(cache: ProcessorCache | undefined): string {\n\tif (cache === 'immutable') return 'public, max-age=31536000, immutable';\n\tif (cache === 'none') return 'no-store';\n\treturn `public, max-age=${cache?.maxAge ?? 3600}`;\n}\n\n/** Where a processor keeps the derivative for one request. */\nexport function derivedKey(\n\tprocessor: Processor<string, any, any, any>,\n\tparams: Readonly<Record<string, string>>,\n\tkey: string,\n): string {\n\treturn `${DERIVED_PREFIX}${fillPattern(processor.parsed, params, key).slice(1)}`;\n}\n\nexport interface ProcessorRequestOptions {\n\tserviceDiscovery: ServiceDiscovery<any>;\n\t/** How the bucket is read through a presigned address. */\n\tfetch?: typeof fetch;\n}\n\n/**\n * Answer one request with the first processor whose pattern matches it, or\n * `undefined` when none does.\n *\n * In order: the parameters are parsed by the processor's schema (400 when it\n * refuses them); the key must be one of the file server's open paths (404\n * otherwise, as an unsigned read of it would be); a derivative already in the\n * bucket is answered without running anything; and only then is the handler\n * run, its `immutable` result written through for next time.\n */\nexport async function handleProcessorRequest(\n\tprocessors: readonly Processor<string, any, any, any>[],\n\trequest: { method: string; path: string },\n\toptions: ProcessorRequestOptions,\n): Promise<ProcessorResponse | undefined> {\n\tconst method = request.method.toUpperCase();\n\n\tfor (const processor of processors) {\n\t\tconst match = matchPattern(processor.parsed, request.path);\n\t\tif (!match) continue;\n\n\t\tif (method !== 'GET' && method !== 'HEAD') {\n\t\t\treturn text(405, 'Method Not Allowed', 'no-store', {\n\t\t\t\tallow: 'GET, HEAD',\n\t\t\t});\n\t\t}\n\n\t\treturn runWithRequestContext(\n\t\t\t{\n\t\t\t\tlogger: processor.logger,\n\t\t\t\trequestId: `processor-${Date.now()}`,\n\t\t\t\tstartTime: Date.now(),\n\t\t\t\toperation: `processor ${processor.pattern}`,\n\t\t\t},\n\t\t\t() => run(processor, match, options),\n\t\t);\n\t}\n\n\treturn undefined;\n}\n\n/**\n * A request handler for a set of processors — what a generated entry serves\n * — with its services discovered from the default environment parser: the\n * process's environment and the credentials `gkm` injected.\n */\nexport function processorServer(\n\tprocessors: readonly Processor<string, any, any, any>[],\n\tenvParser: EnvironmentParser<{}> = defaultEnvParser(),\n): (request: {\n\tmethod: string;\n\tpath: string;\n}) => Promise<ProcessorResponse | undefined> {\n\tconst serviceDiscovery = ServiceDiscovery.getInstance(envParser);\n\treturn (request) =>\n\t\thandleProcessorRequest(processors, request, { serviceDiscovery });\n}\n\nasync function run(\n\tprocessor: Processor<string, any, any, any>,\n\tmatch: { params: Record<string, string>; key: string },\n\toptions: ProcessorRequestOptions,\n): Promise<ProcessorResponse> {\n\tconst logger = processor.logger as Logger;\n\tconst fetcher = options.fetch ?? fetch;\n\tconst { key } = match;\n\n\tconst schema = processor.options.paramsSchema;\n\tlet params: unknown = match.params;\n\tif (schema) {\n\t\tconst parsed = await schema['~standard'].validate(match.params);\n\t\tif (parsed.issues) return text(400, 'Bad Request', SHORT);\n\t\tparams = parsed.value;\n\t}\n\n\t// A derivative is never itself a source, and a private object is never\n\t// processed: a processor serves exactly what an unsigned read would.\n\tif (key.startsWith(DERIVED_PREFIX) || !processor.options.serves(key)) {\n\t\treturn text(404, 'Not Found', SHORT);\n\t}\n\n\tconst services: Record<string, unknown> =\n\t\tawait options.serviceDiscovery.register(processor.services);\n\tconst storage = services[\n\t\tprocessor.options.origin.serviceName\n\t] as StorageClient;\n\n\tconst derived = derivedKey(processor, match.params, key);\n\tconst kept = await read(storage, derived, fetcher);\n\tif (kept) {\n\t\treturn {\n\t\t\tstatus: 200,\n\t\t\theaders: {\n\t\t\t\t'content-type': kept.contentType ?? 'application/octet-stream',\n\t\t\t\t'cache-control': cacheControl('immutable'),\n\t\t\t\t'x-gkm-processor': 'kept',\n\t\t\t},\n\t\t\tbody: new Uint8Array(await kept.response.arrayBuffer()),\n\t\t};\n\t}\n\n\tlet source: Response | undefined;\n\tconst load = async (): Promise<Response> => {\n\t\tif (source) return source;\n\t\tconst found = await read(storage, key, fetcher);\n\t\tif (!found) throw new ProcessorSourceMissing(key);\n\t\tsource = found.response;\n\t\treturn source;\n\t};\n\tconst object: SourceObject = {\n\t\tkey,\n\t\tbytes: async () => new Uint8Array(await (await load()).arrayBuffer()),\n\t\tstream: async () => {\n\t\t\tconst body = (await load()).body;\n\t\t\tif (!body) throw new ProcessorSourceMissing(key);\n\t\t\treturn body;\n\t\t},\n\t\tcontentType: async () =>\n\t\t\t(await load()).headers.get('content-type') ?? undefined,\n\t};\n\n\tlet result: Awaited<ReturnType<typeof processor.handler>>;\n\ttry {\n\t\tresult = await processor.handler({\n\t\t\tparams,\n\t\t\tkey,\n\t\t\tobject,\n\t\t\tlogger,\n\t\t\tservices,\n\t\t} as never);\n\t} catch (error) {\n\t\tif (error instanceof ProcessorSourceMissing) {\n\t\t\treturn text(404, 'Not Found', SHORT);\n\t\t}\n\t\tlogger.error({ err: error, key }, 'Processor failed');\n\t\treturn text(500, 'Internal Server Error', 'no-store');\n\t}\n\n\tconst body =\n\t\ttypeof result.body === 'string'\n\t\t\t? new TextEncoder().encode(result.body)\n\t\t\t: result.body;\n\n\t// Kept only when it can never change: anything else would be served from\n\t// the bucket long after its handler would have answered differently.\n\tif (result.cache === 'immutable') {\n\t\tawait storage\n\t\t\t.upload(derived, Buffer.from(body), result.contentType)\n\t\t\t.catch((error: unknown) =>\n\t\t\t\tlogger.warn({ err: error, key: derived }, 'Could not keep derivative'),\n\t\t\t);\n\t}\n\n\treturn {\n\t\tstatus: 200,\n\t\theaders: {\n\t\t\t'content-type': result.contentType,\n\t\t\t'cache-control': cacheControl(result.cache),\n\t\t\t'x-gkm-processor': 'made',\n\t\t},\n\t\tbody,\n\t};\n}\n\n/** An object through a presigned address, or nothing when it is not there. */\nasync function read(\n\tstorage: StorageClient,\n\tkey: string,\n\tfetcher: typeof fetch,\n): Promise<{ response: Response; contentType?: string } | undefined> {\n\tconst url = await storage.getDownloadURL({ path: key });\n\tconst response = await fetcher(url);\n\tif (!response.ok) {\n\t\tawait response.body?.cancel().catch(() => undefined);\n\t\treturn undefined;\n\t}\n\tconst contentType = response.headers.get('content-type') ?? undefined;\n\treturn { response, ...(contentType ? { contentType } : {}) };\n}\n\nfunction text(\n\tstatus: number,\n\tbody: string,\n\tcache: string,\n\textra: Record<string, string> = {},\n): ProcessorResponse {\n\treturn {\n\t\tstatus,\n\t\theaders: {\n\t\t\t'content-type': 'text/plain; charset=utf-8',\n\t\t\t'cache-control': cache,\n\t\t\t...extra,\n\t\t},\n\t\tbody,\n\t};\n}\n","import type { EnvironmentParser } from '@geekmidas/envkit';\nimport { defaultEnvParser } from '../endpoints/surfaceEnv';\nimport type { Processor } from './Processor';\nimport { processorServer } from './runProcessor';\n\n/** The parts of a Lambda function URL event a processor reads. */\nexport interface FunctionUrlEvent {\n\trawPath: string;\n\trequestContext: { http: { method: string } };\n}\n\n/** What a function URL answers with. */\nexport interface FunctionUrlResult {\n\tstatusCode: number;\n\theaders: Record<string, string>;\n\tbody: string;\n\tisBase64Encoded: boolean;\n}\n\n/**\n * A processor as a Lambda behind a function URL — the CDN's origin for its\n * pattern on AWS. The URL takes IAM auth and the CDN signs each request, so\n * the function cannot be called around the cache.\n */\nexport class AWSLambdaProcessor {\n\tprivate readonly serve: ReturnType<typeof processorServer>;\n\n\tconstructor(\n\t\tprocessor: Processor<string, any, any, any>,\n\t\tenvParser: EnvironmentParser<{}> = defaultEnvParser(),\n\t) {\n\t\tthis.serve = processorServer([processor], envParser);\n\t}\n\n\thandler = async (event: FunctionUrlEvent): Promise<FunctionUrlResult> => {\n\t\tconst response = await this.serve({\n\t\t\tmethod: event.requestContext.http.method,\n\t\t\tpath: event.rawPath,\n\t\t});\n\t\tif (!response) {\n\t\t\treturn {\n\t\t\t\tstatusCode: 404,\n\t\t\t\theaders: { 'cache-control': 'public, max-age=60' },\n\t\t\t\tbody: '',\n\t\t\t\tisBase64Encoded: false,\n\t\t\t};\n\t\t}\n\t\tconst body = response.body ?? '';\n\t\treturn {\n\t\t\tstatusCode: response.status,\n\t\t\theaders: response.headers,\n\t\t\tbody:\n\t\t\t\ttypeof body === 'string' ? body : Buffer.from(body).toString('base64'),\n\t\t\tisBase64Encoded: typeof body !== 'string',\n\t\t};\n\t};\n}\n"],"mappings":";;;;;AAqBA,IAAa,yBAAb,cAA4C,MAAM;CAC5B;CAArB,YAAY,KAAsB;EACjC,MAAM,IAAI,IAAI,wDAAwD;EADlD,KAAA,MAAA;EAEpB,KAAK,OAAO;CACb;AACD;;AAGA,MAAM,QAAQ;;AAGd,SAAgB,aAAa,OAA2C;CACvE,IAAI,UAAU,aAAa,OAAO;CAClC,IAAI,UAAU,QAAQ,OAAO;CAC7B,OAAO,mBAAmB,OAAO,UAAU;AAC5C;;AAGA,SAAgB,WACf,WACA,QACA,KACS;CACT,OAAO,GAAG,i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CACD;AACD"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/processors/runProcessor.ts","../../src/processors/AWSLambdaProcessor.ts"],"sourcesContent":["import type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { runWithRequestContext, ServiceDiscovery } from '@geekmidas/services';\nimport type { ObjectMetadata, StorageClient } from '@geekmidas/storage';\nimport { defaultEnvParser } from '../endpoints/surfaceEnv';\nimport {\n\tDERIVED_PREFIX,\n\ttype Processor,\n\ttype ProcessorCache,\n\ttype SourceObject,\n} from './Processor';\nimport { fillPattern, matchPattern } from './pattern';\n\n/** What a processor answers, for whichever server or function carries it. */\nexport interface ProcessorResponse {\n\tstatus: number;\n\theaders: Record<string, string>;\n\tbody?: Uint8Array | string;\n}\n\n/** The object a request addressed is not in the bucket. */\nexport class ProcessorSourceMissing extends Error {\n\tconstructor(readonly key: string) {\n\t\tsuper(`'${key}' is not in the bucket, so there is nothing to process.`);\n\t\tthis.name = 'ProcessorSourceMissing';\n\t}\n}\n\n/** What a refusal or a miss may be kept for: long enough to absorb a burst. */\nconst SHORT = 'public, max-age=60';\n\n/** The header a response carries, by how long it may be kept. */\nexport function cacheControl(cache: ProcessorCache | undefined): string {\n\tif (cache === 'immutable') return 'public, max-age=31536000, immutable';\n\tif (cache === 'none') return 'no-store';\n\treturn `public, max-age=${cache?.maxAge ?? 3600}`;\n}\n\n/** Where a processor keeps the derivative for one request. */\nexport function derivedKey(\n\tprocessor: Processor<string, any, any, any>,\n\tparams: Readonly<Record<string, string>>,\n\tkey: string,\n): string {\n\treturn `${DERIVED_PREFIX}${fillPattern(processor.parsed, params, key).slice(1)}`;\n}\n\nexport interface ProcessorRequestOptions {\n\tserviceDiscovery: ServiceDiscovery<any>;\n\t/** How the bucket is read through a presigned address. */\n\tfetch?: typeof fetch;\n}\n\n/**\n * Answer one request with the first processor whose pattern matches it, or\n * `undefined` when none does.\n *\n * In order: the parameters are parsed by the processor's schema (400 when it\n * refuses them); the key must be one of the file server's open paths (404\n * otherwise, as an unsigned read of it would be); a derivative already in the\n * bucket is answered without running anything; and only then is the handler\n * run, its `immutable` result written through for next time.\n */\nexport async function handleProcessorRequest(\n\tprocessors: readonly Processor<string, any, any, any>[],\n\trequest: { method: string; path: string },\n\toptions: ProcessorRequestOptions,\n): Promise<ProcessorResponse | undefined> {\n\tconst method = request.method.toUpperCase();\n\n\tfor (const processor of processors) {\n\t\tconst match = matchPattern(processor.parsed, request.path);\n\t\tif (!match) continue;\n\n\t\tif (method !== 'GET' && method !== 'HEAD') {\n\t\t\treturn text(405, 'Method Not Allowed', 'no-store', {\n\t\t\t\tallow: 'GET, HEAD',\n\t\t\t});\n\t\t}\n\n\t\treturn runWithRequestContext(\n\t\t\t{\n\t\t\t\tlogger: processor.logger,\n\t\t\t\trequestId: `processor-${Date.now()}`,\n\t\t\t\tstartTime: Date.now(),\n\t\t\t\toperation: `processor ${processor.pattern}`,\n\t\t\t},\n\t\t\t() => run(processor, match, options),\n\t\t);\n\t}\n\n\treturn undefined;\n}\n\n/**\n * A request handler for a set of processors — what a generated entry serves\n * — with its services discovered from the default environment parser: the\n * process's environment and the credentials `gkm` injected.\n */\nexport function processorServer(\n\tprocessors: readonly Processor<string, any, any, any>[],\n\tenvParser: EnvironmentParser<{}> = defaultEnvParser(),\n): (request: {\n\tmethod: string;\n\tpath: string;\n}) => Promise<ProcessorResponse | undefined> {\n\tconst serviceDiscovery = ServiceDiscovery.getInstance(envParser);\n\treturn (request) =>\n\t\thandleProcessorRequest(processors, request, { serviceDiscovery });\n}\n\nasync function run(\n\tprocessor: Processor<string, any, any, any>,\n\tmatch: { params: Record<string, string>; key: string },\n\toptions: ProcessorRequestOptions,\n): Promise<ProcessorResponse> {\n\tconst logger = processor.logger as Logger;\n\tconst fetcher = options.fetch ?? fetch;\n\tconst { key } = match;\n\n\tconst schema = processor.options.paramsSchema;\n\tlet params: unknown = match.params;\n\tif (schema) {\n\t\tconst parsed = await schema['~standard'].validate(match.params);\n\t\tif (parsed.issues) return text(400, 'Bad Request', SHORT);\n\t\tparams = parsed.value;\n\t}\n\n\t// A derivative is never itself a source, and a private object is never\n\t// processed: a processor serves exactly what an unsigned read would.\n\tif (key.startsWith(DERIVED_PREFIX) || !processor.options.serves(key)) {\n\t\treturn text(404, 'Not Found', SHORT);\n\t}\n\n\tconst services: Record<string, unknown> =\n\t\tawait options.serviceDiscovery.register(processor.services);\n\tconst storage = services[\n\t\tprocessor.options.origin.serviceName\n\t] as StorageClient;\n\n\tconst derived = derivedKey(processor, match.params, key);\n\tconst kept = await read(storage, derived, fetcher);\n\tif (kept) {\n\t\treturn {\n\t\t\tstatus: 200,\n\t\t\theaders: {\n\t\t\t\t'content-type': kept.contentType ?? 'application/octet-stream',\n\t\t\t\t'cache-control': cacheControl('immutable'),\n\t\t\t\t'x-gkm-processor': 'kept',\n\t\t\t},\n\t\t\tbody: new Uint8Array(await kept.response.arrayBuffer()),\n\t\t};\n\t}\n\n\tlet source: Response | undefined;\n\tconst load = async (): Promise<Response> => {\n\t\tif (source) return source;\n\t\tconst found = await read(storage, key, fetcher);\n\t\tif (!found) throw new ProcessorSourceMissing(key);\n\t\tsource = found.response;\n\t\treturn source;\n\t};\n\t// One HEAD, shared by everything that asks about the object rather than\n\t// for it — a size guard never downloads what it is guarding against.\n\tlet head: Promise<ObjectMetadata> | undefined;\n\tconst metadata = (): Promise<ObjectMetadata> => {\n\t\thead ??= storage.head(key).then((found) => {\n\t\t\tif (!found) throw new ProcessorSourceMissing(key);\n\t\t\treturn found;\n\t\t});\n\t\treturn head;\n\t};\n\tconst object: SourceObject = {\n\t\tkey,\n\t\tsize: async () => (await metadata()).size,\n\t\tmetadata,\n\t\tbytes: async () => new Uint8Array(await (await load()).arrayBuffer()),\n\t\tstream: async () => {\n\t\t\tconst body = (await load()).body;\n\t\t\tif (!body) throw new ProcessorSourceMissing(key);\n\t\t\treturn body;\n\t\t},\n\t\tcontentType: async () =>\n\t\t\tsource\n\t\t\t\t? (source.headers.get('content-type') ?? undefined)\n\t\t\t\t: (await metadata()).contentType,\n\t};\n\n\tlet result: Awaited<ReturnType<typeof processor.handler>>;\n\ttry {\n\t\tresult = await processor.handler({\n\t\t\tparams,\n\t\t\tkey,\n\t\t\tobject,\n\t\t\tlogger,\n\t\t\tservices,\n\t\t} as never);\n\t} catch (error) {\n\t\tif (error instanceof ProcessorSourceMissing) {\n\t\t\treturn text(404, 'Not Found', SHORT);\n\t\t}\n\t\tlogger.error({ err: error, key }, 'Processor failed');\n\t\treturn text(500, 'Internal Server Error', 'no-store');\n\t}\n\n\tconst body =\n\t\ttypeof result.body === 'string'\n\t\t\t? new TextEncoder().encode(result.body)\n\t\t\t: result.body;\n\n\t// Kept only when it can never change: anything else would be served from\n\t// the bucket long after its handler would have answered differently.\n\tif (result.cache === 'immutable') {\n\t\tawait storage\n\t\t\t.upload(derived, Buffer.from(body), result.contentType)\n\t\t\t.catch((error: unknown) =>\n\t\t\t\tlogger.warn({ err: error, key: derived }, 'Could not keep derivative'),\n\t\t\t);\n\t}\n\n\treturn {\n\t\tstatus: 200,\n\t\theaders: {\n\t\t\t'content-type': result.contentType,\n\t\t\t'cache-control': cacheControl(result.cache),\n\t\t\t'x-gkm-processor': 'made',\n\t\t},\n\t\tbody,\n\t};\n}\n\n/** An object through a presigned address, or nothing when it is not there. */\nasync function read(\n\tstorage: StorageClient,\n\tkey: string,\n\tfetcher: typeof fetch,\n): Promise<{ response: Response; contentType?: string } | undefined> {\n\tconst url = await storage.getDownloadURL({ path: key });\n\tconst response = await fetcher(url);\n\tif (!response.ok) {\n\t\tawait response.body?.cancel().catch(() => undefined);\n\t\treturn undefined;\n\t}\n\tconst contentType = response.headers.get('content-type') ?? undefined;\n\treturn { response, ...(contentType ? { contentType } : {}) };\n}\n\nfunction text(\n\tstatus: number,\n\tbody: string,\n\tcache: string,\n\textra: Record<string, string> = {},\n): ProcessorResponse {\n\treturn {\n\t\tstatus,\n\t\theaders: {\n\t\t\t'content-type': 'text/plain; charset=utf-8',\n\t\t\t'cache-control': cache,\n\t\t\t...extra,\n\t\t},\n\t\tbody,\n\t};\n}\n","import type { EnvironmentParser } from '@geekmidas/envkit';\nimport { defaultEnvParser } from '../endpoints/surfaceEnv';\nimport type { Processor } from './Processor';\nimport { processorServer } from './runProcessor';\n\n/** The parts of a Lambda function URL event a processor reads. */\nexport interface FunctionUrlEvent {\n\trawPath: string;\n\trequestContext: { http: { method: string } };\n}\n\n/** What a function URL answers with. */\nexport interface FunctionUrlResult {\n\tstatusCode: number;\n\theaders: Record<string, string>;\n\tbody: string;\n\tisBase64Encoded: boolean;\n}\n\n/**\n * A processor as a Lambda behind a function URL — the CDN's origin for its\n * pattern on AWS. The URL takes IAM auth and the CDN signs each request, so\n * the function cannot be called around the cache.\n */\nexport class AWSLambdaProcessor {\n\tprivate readonly serve: ReturnType<typeof processorServer>;\n\n\tconstructor(\n\t\tprocessor: Processor<string, any, any, any>,\n\t\tenvParser: EnvironmentParser<{}> = defaultEnvParser(),\n\t) {\n\t\tthis.serve = processorServer([processor], envParser);\n\t}\n\n\thandler = async (event: FunctionUrlEvent): Promise<FunctionUrlResult> => {\n\t\tconst response = await this.serve({\n\t\t\tmethod: event.requestContext.http.method,\n\t\t\tpath: event.rawPath,\n\t\t});\n\t\tif (!response) {\n\t\t\treturn {\n\t\t\t\tstatusCode: 404,\n\t\t\t\theaders: { 'cache-control': 'public, max-age=60' },\n\t\t\t\tbody: '',\n\t\t\t\tisBase64Encoded: false,\n\t\t\t};\n\t\t}\n\t\tconst body = response.body ?? '';\n\t\treturn {\n\t\t\tstatusCode: response.status,\n\t\t\theaders: response.headers,\n\t\t\tbody:\n\t\t\t\ttypeof body === 'string' ? body : Buffer.from(body).toString('base64'),\n\t\t\tisBase64Encoded: typeof body !== 'string',\n\t\t};\n\t};\n}\n"],"mappings":";;;;;AAqBA,IAAa,yBAAb,cAA4C,MAAM;CAC5B;CAArB,YAAY,KAAsB;EACjC,MAAM,IAAI,IAAI,wD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,WACA,YAAmC,iBAAiB,GACnD;EACD,KAAK,QAAQ,gBAAgB,CAAC,SAAS,GAAG,SAAS;CACpD;CAEA,UAAU,OAAO,UAAwD;EACxE,MAAM,WAAW,MAAM,KAAK,MAAM;GACjC,QAAQ,MAAM,eAAe,KAAK;GAClC,MAAM,MAAM;EACb,CAAC;EACD,IAAI,CAAC,UACJ,OAAO;GACN,YAAY;GACZ,SAAS,EAAE,iBAAiB,qBAAqB;GACjD,MAAM;GACN,iBAAiB;EAClB;EAED,MAAM,OAAO,SAAS,QAAQ;EAC9B,OAAO;GACN,YAAY,SAAS;GACrB,SAAS,SAAS;GAClB,MACC,OAAO,SAAS,WAAW,OAAO,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS,QAAQ;GACtE,iBAAiB,OAAO,SAAS;EAClC;CACD;AACD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geekmidas/constructs",
3
- "version": "10.0.0-alpha.184",
3
+ "version": "10.0.0-alpha.186",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "exports": {
@@ -345,13 +345,13 @@
345
345
  "lodash.uniqby": "~4.7.0",
346
346
  "openapi-types": "~12.1.3",
347
347
  "qs": "~6.16.0",
348
- "@geekmidas/envkit": ">=10.0.0-alpha.184 <10.0.0",
349
- "@geekmidas/errors": ">=10.0.0-alpha.184 <10.0.0",
350
- "@geekmidas/events": ">=10.0.0-alpha.184 <10.0.0",
351
- "@geekmidas/logger": ">=10.0.0-alpha.184 <10.0.0",
352
- "@geekmidas/manifest": ">=10.0.0-alpha.184 <10.0.0",
353
- "@geekmidas/schema": ">=10.0.0-alpha.184 <10.0.0",
354
- "@geekmidas/services": ">=10.0.0-alpha.184 <10.0.0"
348
+ "@geekmidas/envkit": ">=10.0.0-alpha.186 <10.0.0",
349
+ "@geekmidas/errors": ">=10.0.0-alpha.186 <10.0.0",
350
+ "@geekmidas/events": ">=10.0.0-alpha.186 <10.0.0",
351
+ "@geekmidas/logger": ">=10.0.0-alpha.186 <10.0.0",
352
+ "@geekmidas/manifest": ">=10.0.0-alpha.186 <10.0.0",
353
+ "@geekmidas/schema": ">=10.0.0-alpha.186 <10.0.0",
354
+ "@geekmidas/services": ">=10.0.0-alpha.186 <10.0.0"
355
355
  },
356
356
  "devDependencies": {
357
357
  "@aws-sdk/client-apigatewaymanagementapi": "~3.1136.0",
@@ -374,20 +374,20 @@
374
374
  "pg": "~8.23.0",
375
375
  "ws": "~8.22.0",
376
376
  "zod": "~4.6.5",
377
- "@geekmidas/audit": ">=10.0.0-alpha.184 <10.0.0",
378
- "@geekmidas/auth": "10.0.0-alpha.184",
379
- "@geekmidas/cache": ">=10.0.0-alpha.184 <10.0.0",
380
- "@geekmidas/db": ">=10.0.0-alpha.184 <10.0.0",
381
- "@geekmidas/emailkit": ">=10.0.0-alpha.184 <10.0.0",
382
- "@geekmidas/envkit": ">=10.0.0-alpha.184 <10.0.0",
383
- "@geekmidas/errors": ">=10.0.0-alpha.184 <10.0.0",
384
- "@geekmidas/events": ">=10.0.0-alpha.184 <10.0.0",
385
- "@geekmidas/logger": ">=10.0.0-alpha.184 <10.0.0",
386
- "@geekmidas/rate-limit": ">=10.0.0-alpha.184 <10.0.0",
387
- "@geekmidas/schema": ">=10.0.0-alpha.184 <10.0.0",
388
- "@geekmidas/services": ">=10.0.0-alpha.184 <10.0.0",
389
- "@geekmidas/telescope": "10.0.0-alpha.184",
390
- "@geekmidas/testkit": ">=10.0.0-alpha.184 <10.0.0"
377
+ "@geekmidas/audit": ">=10.0.0-alpha.186 <10.0.0",
378
+ "@geekmidas/auth": "10.0.0-alpha.186",
379
+ "@geekmidas/cache": ">=10.0.0-alpha.186 <10.0.0",
380
+ "@geekmidas/db": ">=10.0.0-alpha.186 <10.0.0",
381
+ "@geekmidas/emailkit": ">=10.0.0-alpha.186 <10.0.0",
382
+ "@geekmidas/envkit": ">=10.0.0-alpha.186 <10.0.0",
383
+ "@geekmidas/errors": ">=10.0.0-alpha.186 <10.0.0",
384
+ "@geekmidas/events": ">=10.0.0-alpha.186 <10.0.0",
385
+ "@geekmidas/logger": ">=10.0.0-alpha.186 <10.0.0",
386
+ "@geekmidas/rate-limit": ">=10.0.0-alpha.186 <10.0.0",
387
+ "@geekmidas/schema": ">=10.0.0-alpha.186 <10.0.0",
388
+ "@geekmidas/services": ">=10.0.0-alpha.186 <10.0.0",
389
+ "@geekmidas/telescope": "10.0.0-alpha.186",
390
+ "@geekmidas/testkit": ">=10.0.0-alpha.186 <10.0.0"
391
391
  },
392
392
  "peerDependencies": {
393
393
  "@aws-sdk/client-apigatewaymanagementapi": ">=3.1136.0",
@@ -403,15 +403,15 @@
403
403
  "msw": ">=2.15.0",
404
404
  "pg": ">=8.23.0",
405
405
  "ws": ">=8.22.0",
406
- "@geekmidas/audit": ">=10.0.0-alpha.184 <10.0.0",
407
- "@geekmidas/auth": "10.0.0-alpha.184",
408
- "@geekmidas/cache": ">=10.0.0-alpha.184 <10.0.0",
409
- "@geekmidas/db": ">=10.0.0-alpha.184 <10.0.0",
410
- "@geekmidas/emailkit": ">=10.0.0-alpha.184 <10.0.0",
411
- "@geekmidas/rate-limit": ">=10.0.0-alpha.184 <10.0.0",
412
- "@geekmidas/storage": ">=10.0.0-alpha.184 <10.0.0",
413
- "@geekmidas/telescope": "10.0.0-alpha.184",
414
- "@geekmidas/testkit": ">=10.0.0-alpha.184 <10.0.0"
406
+ "@geekmidas/audit": ">=10.0.0-alpha.186 <10.0.0",
407
+ "@geekmidas/auth": "10.0.0-alpha.186",
408
+ "@geekmidas/cache": ">=10.0.0-alpha.186 <10.0.0",
409
+ "@geekmidas/db": ">=10.0.0-alpha.186 <10.0.0",
410
+ "@geekmidas/emailkit": ">=10.0.0-alpha.186 <10.0.0",
411
+ "@geekmidas/rate-limit": ">=10.0.0-alpha.186 <10.0.0",
412
+ "@geekmidas/storage": ">=10.0.0-alpha.186 <10.0.0",
413
+ "@geekmidas/telescope": "10.0.0-alpha.186",
414
+ "@geekmidas/testkit": ">=10.0.0-alpha.186 <10.0.0"
415
415
  },
416
416
  "peerDependenciesMeta": {
417
417
  "@aws-sdk/client-apigatewaymanagementapi": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"ProcessorBuilder-CdLwJK4k.d.mts","names":[],"sources":["../src/processors/pattern.ts","../src/processors/Processor.ts","../src/processors/ProcessorBuilder.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;KAeY,kBAAkB,oBAC7B,8BAA8B,cAAc,SACzC,OAAO,sBAAsB;;KAIrB,cAAc,uBACxB,KAAK,kBAAkB;;cAIZ,gCAAgC;WAElC;WACA;EAFV,YACU,iBACA;;;UAYM;WACP;;WAEA;IACJ;IAAiB;;IACjB;IAAe;;;WAGX;;WAEA;;;iBAIM,aAAa,kBAAkB;;UAkE9B;EAChB,QAAQ;EACR;;;;;;iBAOe,aACf,QAAQ,eACR,eACE;;iBA0Ba,YACf,QAAQ,eACR,QAAQ,SAAS,kCACjB;;cAmBY,8BAA8B;WAEhC;WACA;EAFV,YACU,iBACA;;;;;KCtKC;;;;;EAIP;;;;;UAKY;EAChB,MAAM;EACN;;;;;EAKA,QAAQ;;;UAIQ;WACP;EACT,SAAS,QAAQ;EACjB,UAAU,QAAQ,eAAe;;EAEjC,eAAe;;UAGC,iBAChB,SACA,kBAAkB,WAClB,gBAAgB;EAEhB,QAAQ;EACR;EACA,QAAQ;EACR,QAAQ;EACR,UAAU,cAAc;;KAGb,iBACX,SACA,kBAAkB,WAClB,gBAAgB,WAEhB,SAAS,iBAAiB,SAAS,WAAW,aAC1C,QAAQ,mBAAmB;;KAGpB,gBACX,yBACA,gBAAgB,gCACb,gBAAgB,mBACjB,oBAAoB,WACpB,cAAc;;;;;;;;;;cAWJ,UACZ,kCACA,gBAAgB,0CAChB,kBAAkB,gBAClB,gBAAgB,SAAS,gBAChB,UAAU,oBAAoB;WAY7B,QAAQ;WACR,SAAS,iBACjB,gBAAgB,UAAU,UAC1B,WACA;WAEQ;;IAER;;IAEA;;IAEA,QAAQ,gBAAgB;;IAExB,SAAS;IACT,eAAe;;IAEf;IACA,QAAQ;IACR,UAAU;IACV;IACA;IACA;;EAjCF;SAEO,YAAY,eAAe,OAAO;EAQzC,YACU,QAAQ,eACR,SAAS,iBACjB,gBAAgB,UAAU,UAC1B,WACA,UAEQ;;IAER;;IAEA;;IAEA,QAAQ,gBAAgB;;IAExB,SAAS;IACT,eAAe;;IAEf;IACA,QAAQ;IACR,UAAU;IACV;IACA;IACA;;;MAsBE,WAAW;;MAKX;MAIA;MAIA;MAIA;;;;;cC/IQ,+BAA+B;WACtB;EAArB,YAAqB;;UAUZ,sBAAsB,gBAAgB;EAC/C,QAAQ;EACR;EACA;EACA,QAAQ,gBAAgB;EACxB,SAAS;EACT,QAAQ;EACR,eAAe;EACf;EACA,UAAU;EACV;EACA;EACA;;;;;;cAOY,iBACZ,yBACA,gBAAgB,0CAChB,kBAAkB,gBAClB,gBAAgB,SAAS;mBAEI;EAA7B,YAA6B,OAAO,sBAAsB;;;;;EAM1D,OAAO,UAAU,kBAChB,QAAQ,IACN,iBAAiB,UAAU,GAAG,WAAW;;EAK5C,gBAAgB,mBAAmB,cAClC,YAAY,IACV,iBACF,UACA,aACI,cAAc,WAAW,KAC7B;;;;;;EAqBD,OAAO;;EAaP,QAAQ;;EAKR,WAAW;EAIX,OACC,IAAI,iBACH,gBAAgB,UAAU,UAC1B,WACA,WAEC,UAAU,UAAU,SAAS,WAAW"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"ProcessorBuilder-ClD7tmEe.d.cts","names":[],"sources":["../src/processors/pattern.ts","../src/processors/Processor.ts","../src/processors/ProcessorBuilder.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;KAeY,kBAAkB,oBAC7B,8BAA8B,cAAc,SACzC,OAAO,sBAAsB;;KAIrB,cAAc,uBACxB,KAAK,kBAAkB;;cAIZ,gCAAgC;WAElC;WACA;EAFV,YACU,iBACA;;;UAYM;WACP;;WAEA;IACJ;IAAiB;;I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