@farm.js/integration-utils 0.1.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Farm.js Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
package/README.md ADDED
@@ -0,0 +1,11 @@
1
+ # @farm.js/integration-utils
2
+
3
+ Shared integration utilities for Farm.js
4
+
5
+ Farm.js is currently in beta.
6
+
7
+ ```bash
8
+ npm install @farm.js/integration-utils@beta
9
+ ```
10
+
11
+ See the [Farm.js repository](https://github.com/farming-labs/farm.js) for documentation, examples, and support.
@@ -0,0 +1,12 @@
1
+ import type { FarmIntegrationConfigDefinition } from "@farm.js/core";
2
+ type ConfigKey<TConfig> = Extract<keyof TConfig, string>;
3
+ export interface ResolvedIntegrationConfigOptions<TConfig extends object> {
4
+ label: string;
5
+ env?: Partial<Record<ConfigKey<TConfig>, string | readonly string[]>>;
6
+ defaults?: Partial<TConfig>;
7
+ input?: Partial<TConfig>;
8
+ required?: readonly ConfigKey<TConfig>[];
9
+ }
10
+ export declare function integrationConfig<TConfig extends object>(options: ResolvedIntegrationConfigOptions<TConfig>): FarmIntegrationConfigDefinition<TConfig>;
11
+ export {};
12
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,eAAe,CAAC;AAErE,KAAK,SAAS,CAAC,OAAO,IAAI,OAAO,CAAC,MAAM,OAAO,EAAE,MAAM,CAAC,CAAC;AAEzD,MAAM,WAAW,gCAAgC,CAAC,OAAO,SAAS,MAAM;IACtE,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,CAAC,CAAC,CAAC;IACtE,QAAQ,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;IAC5B,KAAK,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;IACzB,QAAQ,CAAC,EAAE,SAAS,SAAS,CAAC,OAAO,CAAC,EAAE,CAAC;CAC1C;AAED,wBAAgB,iBAAiB,CAAC,OAAO,SAAS,MAAM,EACtD,OAAO,EAAE,gCAAgC,CAAC,OAAO,CAAC,GACjD,+BAA+B,CAAC,OAAO,CAAC,CAiC1C"}
package/dist/config.js ADDED
@@ -0,0 +1,37 @@
1
+ export function integrationConfig(options) {
2
+ return {
3
+ env: options.env,
4
+ defaults: options.defaults,
5
+ input: options.input,
6
+ schema: {
7
+ safeParse(value) {
8
+ const data = (isObject(value) ? value : {});
9
+ const issues = options.required
10
+ ?.filter((key) => isMissingConfigValue(data[key]))
11
+ .map((key) => ({
12
+ path: [key],
13
+ code: "required",
14
+ message: `${options.label} requires ${String(key)}.`,
15
+ })) ?? [];
16
+ if (issues.length > 0) {
17
+ return {
18
+ success: false,
19
+ error: {
20
+ issues,
21
+ },
22
+ };
23
+ }
24
+ return {
25
+ success: true,
26
+ data,
27
+ };
28
+ },
29
+ },
30
+ };
31
+ }
32
+ function isObject(value) {
33
+ return !!value && typeof value === "object" && !Array.isArray(value);
34
+ }
35
+ function isMissingConfigValue(value) {
36
+ return value === undefined || value === null || value === "";
37
+ }
@@ -0,0 +1,19 @@
1
+ export interface ParsedCookie {
2
+ name: string;
3
+ value: string;
4
+ }
5
+ export interface RequestCookieOptions {
6
+ maxAge?: number;
7
+ httpOnly?: boolean;
8
+ sameSite?: "Lax" | "Strict" | "None";
9
+ path?: string;
10
+ secure?: boolean;
11
+ domain?: string;
12
+ expires?: Date;
13
+ }
14
+ export declare function parseCookieHeaderMap(header: string | null): Record<string, string>;
15
+ export declare function parseCookieHeaderList(header: string | null): ParsedCookie[];
16
+ export declare function getCookieValue(headers: Headers, name: string): string | null;
17
+ export declare function createRequestCookie(name: string, value: string, request: Request, options?: RequestCookieOptions): string;
18
+ export declare function clearRequestCookie(name: string, request: Request, options?: Omit<RequestCookieOptions, "maxAge">): string;
19
+ //# sourceMappingURL=cookies.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cookies.d.ts","sourceRoot":"","sources":["../src/cookies.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,oBAAoB;IACnC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,QAAQ,CAAC,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;IACrC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,IAAI,CAAC;CAChB;AAED,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAelF;AAED,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,YAAY,EAAE,CAK3E;AAED,wBAAgB,cAAc,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAE5E;AAED,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,OAAO,EAChB,OAAO,GAAE,oBAAyB,GACjC,MAAM,CA4BR;AAED,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,OAAO,EAChB,OAAO,GAAE,IAAI,CAAC,oBAAoB,EAAE,QAAQ,CAAM,GACjD,MAAM,CAKR"}
@@ -0,0 +1,50 @@
1
+ export function parseCookieHeaderMap(header) {
2
+ if (!header) {
3
+ return {};
4
+ }
5
+ return Object.fromEntries(header
6
+ .split(";")
7
+ .map((part) => part.trim())
8
+ .filter(Boolean)
9
+ .map((part) => {
10
+ const [key, ...rest] = part.split("=");
11
+ return [key, decodeURIComponent(rest.join("="))];
12
+ }));
13
+ }
14
+ export function parseCookieHeaderList(header) {
15
+ return Object.entries(parseCookieHeaderMap(header)).map(([name, value]) => ({
16
+ name,
17
+ value,
18
+ }));
19
+ }
20
+ export function getCookieValue(headers, name) {
21
+ return parseCookieHeaderMap(headers.get("cookie"))[name] ?? null;
22
+ }
23
+ export function createRequestCookie(name, value, request, options = {}) {
24
+ const requestUrl = new URL(request.url);
25
+ const secure = options.secure ?? requestUrl.protocol === "https:";
26
+ const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${options.path || "/"}`];
27
+ if (options.maxAge != null) {
28
+ parts.push(`Max-Age=${Math.max(0, Math.floor(options.maxAge))}`);
29
+ }
30
+ if (options.domain) {
31
+ parts.push(`Domain=${options.domain}`);
32
+ }
33
+ if (options.expires) {
34
+ parts.push(`Expires=${options.expires.toUTCString()}`);
35
+ }
36
+ if (options.httpOnly !== false) {
37
+ parts.push("HttpOnly");
38
+ }
39
+ if (secure) {
40
+ parts.push("Secure");
41
+ }
42
+ parts.push(`SameSite=${options.sameSite || "Lax"}`);
43
+ return parts.join("; ");
44
+ }
45
+ export function clearRequestCookie(name, request, options = {}) {
46
+ return createRequestCookie(name, "", request, {
47
+ ...options,
48
+ maxAge: 0,
49
+ });
50
+ }
package/dist/html.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export declare function escapeHtml(value: string): string;
2
+ //# sourceMappingURL=html.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"html.d.ts","sourceRoot":"","sources":["../src/html.ts"],"names":[],"mappings":"AAAA,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAOhD"}
package/dist/html.js ADDED
@@ -0,0 +1,8 @@
1
+ export function escapeHtml(value) {
2
+ return value
3
+ .replaceAll("&", "&amp;")
4
+ .replaceAll("<", "&lt;")
5
+ .replaceAll(">", "&gt;")
6
+ .replaceAll('"', "&quot;")
7
+ .replaceAll("'", "&#39;");
8
+ }
@@ -0,0 +1,9 @@
1
+ export { escapeHtml } from "./html.js";
2
+ export { integrationConfig } from "./config.js";
3
+ export { createAuthRouteIntegration, createPathInferredClientApi, methodNotAllowed, } from "./integration.js";
4
+ export { createDocumentNavigationMatchers, normalizeMatchers } from "./matchers.js";
5
+ export { clearRequestCookie, createRequestCookie, getCookieValue, parseCookieHeaderList, parseCookieHeaderMap, } from "./cookies.js";
6
+ export { getOrigin, getReturnTo, resolveAppPath, resolveCallbackSettings, toAbsoluteUrl, withSearchParams, } from "./url.js";
7
+ export { normalizeWebhookConfig } from "./webhooks.js";
8
+ export type { FarmNormalizedWebhookDefinition, FarmWebhookAckResult, FarmWebhookConfig, FarmWebhookContext, FarmWebhookDefinition, FarmWebhookEvent, } from "./webhooks.js";
9
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EACL,0BAA0B,EAC1B,2BAA2B,EAC3B,gBAAgB,GACjB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,gCAAgC,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACpF,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,cAAc,EACd,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,SAAS,EACT,WAAW,EACX,cAAc,EACd,uBAAuB,EACvB,aAAa,EACb,gBAAgB,GACjB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AACvD,YAAY,EACV,+BAA+B,EAC/B,oBAAoB,EACpB,iBAAiB,EACjB,kBAAkB,EAClB,qBAAqB,EACrB,gBAAgB,GACjB,MAAM,eAAe,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export { escapeHtml } from "./html.js";
2
+ export { integrationConfig } from "./config.js";
3
+ export { createAuthRouteIntegration, createPathInferredClientApi, methodNotAllowed, } from "./integration.js";
4
+ export { createDocumentNavigationMatchers, normalizeMatchers } from "./matchers.js";
5
+ export { clearRequestCookie, createRequestCookie, getCookieValue, parseCookieHeaderList, parseCookieHeaderMap, } from "./cookies.js";
6
+ export { getOrigin, getReturnTo, resolveAppPath, resolveCallbackSettings, toAbsoluteUrl, withSearchParams, } from "./url.js";
7
+ export { normalizeWebhookConfig } from "./webhooks.js";
@@ -0,0 +1,47 @@
1
+ import { type FarmIntegrationHandlerContext, type FarmIntegrationAPIOperation, type FarmIntegrationLogger, type FarmIntegrationRouteMethod } from "@farm.js/core";
2
+ export interface AuthRouteIntegrationConfig<TInstance> {
3
+ type: string;
4
+ instance: TInstance;
5
+ log?: FarmIntegrationLogger;
6
+ path: string;
7
+ methods: FarmIntegrationRouteMethod[];
8
+ handler: (request: Request, context: FarmIntegrationHandlerContext, instance: TInstance) => Promise<Response> | Response;
9
+ }
10
+ export declare function createAuthRouteIntegration<TInstance>(config: AuthRouteIntegrationConfig<TInstance>): import("@farm.js/core").DefinedIntegration<{
11
+ category: "auth";
12
+ type: string;
13
+ instance: TInstance;
14
+ log: FarmIntegrationLogger | undefined;
15
+ routes: {
16
+ path: string;
17
+ methods: FarmIntegrationRouteMethod[];
18
+ handler(request: Request, context: FarmIntegrationHandlerContext): Response | Promise<Response>;
19
+ }[];
20
+ }>;
21
+ export declare function methodNotAllowed(allow: readonly string[]): Response;
22
+ export interface PathInferredClientOperation<TPath extends string = string, TOperation extends FarmIntegrationAPIOperation<any, any, any, any> = FarmIntegrationAPIOperation<any, any, any, any>, TLeafName extends string | undefined = undefined> {
23
+ path: TPath;
24
+ operation: TOperation;
25
+ leafName?: TLeafName;
26
+ }
27
+ type ReplaceLeafSegment<TPath extends string, TLeafName extends string | undefined = undefined> = TLeafName extends string ? TPath extends `${infer TBase}/${string}` ? `${TBase}/${TLeafName}` : TLeafName : TPath;
28
+ type StripClientRoutePrefix<TPath extends string> = TPath extends `/api/${string}/${infer TRest}` ? TRest : TPath extends `/${string}/${infer TRest}` ? TRest : TPath extends `/${infer TRest}` ? TRest : TPath;
29
+ type CamelCaseRouteSegment<TSegment extends string> = TSegment extends `${infer THead}-${infer TTail}` ? `${THead}${Capitalize<CamelCaseRouteSegment<TTail>>}` : TSegment;
30
+ type NormalizeClientRouteSegmentType<TSegment extends string> = TSegment extends `[...${infer TName}]` ? TName : TSegment extends `[${infer TName}]` ? TName : TSegment extends `${infer TName}(${string}` ? TName : CamelCaseRouteSegment<TSegment>;
31
+ type RouteNamespaceFromClientPath<TPath extends string, TOperation extends FarmIntegrationAPIOperation<any, any, any, any>> = TPath extends `${infer THead}/${infer TTail}` ? {
32
+ [TKey in NormalizeClientRouteSegmentType<THead>]: RouteNamespaceFromClientPath<TTail, TOperation>;
33
+ } : {
34
+ [TKey in NormalizeClientRouteSegmentType<TPath>]: {
35
+ [TMethod in Lowercase<TOperation["method"] & string>]: TOperation;
36
+ };
37
+ };
38
+ type UnionToIntersection<TUnion> = (TUnion extends unknown ? (value: TUnion) => void : never) extends (value: infer TIntersection) => void ? TIntersection : never;
39
+ type ExpandRecursively<TValue> = TValue extends (...args: any[]) => any ? TValue : TValue extends object ? {
40
+ [TKey in keyof TValue]: ExpandRecursively<TValue[TKey]>;
41
+ } : TValue;
42
+ type PathEntryToAPI<TEntry extends PathInferredClientOperation<string, any, any>> = TEntry extends PathInferredClientOperation<infer TPath extends string, infer TOperation extends FarmIntegrationAPIOperation<any, any, any, any>, infer TLeafName extends string | undefined> ? RouteNamespaceFromClientPath<StripClientRoutePrefix<ReplaceLeafSegment<TPath, TLeafName>>, TOperation> : never;
43
+ type PathEntriesToAPI<TEntries extends readonly PathInferredClientOperation<string, any, any>[]> = ExpandRecursively<UnionToIntersection<PathEntryToAPI<TEntries[number]>>>;
44
+ export type InferPathInferredClientAPI<TEntries extends readonly PathInferredClientOperation<string, any, any>[]> = PathEntriesToAPI<TEntries>;
45
+ export declare function createPathInferredClientApi<const TEntries extends readonly PathInferredClientOperation<string, any, any>[]>(...entries: TEntries): InferPathInferredClientAPI<TEntries>;
46
+ export {};
47
+ //# sourceMappingURL=integration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"integration.d.ts","sourceRoot":"","sources":["../src/integration.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,6BAA6B,EAClC,KAAK,2BAA2B,EAChC,KAAK,qBAAqB,EAC1B,KAAK,0BAA0B,EAChC,MAAM,eAAe,CAAC;AAGvB,MAAM,WA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1,87 @@
1
+ import { defineIntegration, defineIntegrationAPI, } from "@farm.js/core";
2
+ export function createAuthRouteIntegration(config) {
3
+ return defineIntegration({
4
+ category: "auth",
5
+ type: config.type,
6
+ instance: config.instance,
7
+ log: config.log,
8
+ routes: [
9
+ {
10
+ path: config.path,
11
+ methods: config.methods,
12
+ handler(request, context) {
13
+ return config.handler(request, context, config.instance);
14
+ },
15
+ },
16
+ ],
17
+ });
18
+ }
19
+ export function methodNotAllowed(allow) {
20
+ return new Response("Method Not Allowed", {
21
+ status: 405,
22
+ headers: {
23
+ Allow: allow.join(", "),
24
+ },
25
+ });
26
+ }
27
+ function normalizeClientRouteSegment(segment) {
28
+ if (!segment) {
29
+ return segment;
30
+ }
31
+ if (segment.startsWith("[...") && segment.endsWith("]")) {
32
+ return segment.slice(4, -1);
33
+ }
34
+ if (segment.startsWith("[") && segment.endsWith("]")) {
35
+ return segment.slice(1, -1);
36
+ }
37
+ const groupIndex = segment.indexOf("(");
38
+ if (groupIndex > 0) {
39
+ segment = segment.slice(0, groupIndex);
40
+ }
41
+ return segment.replace(/-([a-zA-Z0-9])/g, (_match, char) => char.toUpperCase());
42
+ }
43
+ function getClientSegmentsFromPath(path) {
44
+ const segments = path.split("/").filter(Boolean);
45
+ if (segments.length === 0) {
46
+ return ["index"];
47
+ }
48
+ const stripped = segments[0] === "api" && segments.length > 2
49
+ ? segments.slice(2)
50
+ : segments.length > 1
51
+ ? segments.slice(1)
52
+ : [segments[segments.length - 1]];
53
+ return stripped.map(normalizeClientRouteSegment).filter(Boolean);
54
+ }
55
+ function setClientOperation(target, segments, operation) {
56
+ const [head, ...tail] = segments;
57
+ if (!head) {
58
+ return;
59
+ }
60
+ if (tail.length === 0) {
61
+ const leaf = (target[head] || {});
62
+ leaf[operation.method.toLowerCase()] = {
63
+ ...operation,
64
+ path: operation.path,
65
+ __pathless: false,
66
+ };
67
+ target[head] = leaf;
68
+ return;
69
+ }
70
+ const branch = (target[head] || {});
71
+ target[head] = branch;
72
+ setClientOperation(branch, tail, operation);
73
+ }
74
+ export function createPathInferredClientApi(...entries) {
75
+ const api = {};
76
+ for (const entry of entries) {
77
+ const segments = getClientSegmentsFromPath(entry.path);
78
+ if (segments.length === 0) {
79
+ continue;
80
+ }
81
+ if (entry.leafName) {
82
+ segments[segments.length - 1] = entry.leafName;
83
+ }
84
+ setClientOperation(api, segments, entry.operation);
85
+ }
86
+ return defineIntegrationAPI(api);
87
+ }
@@ -0,0 +1,3 @@
1
+ export declare function normalizeMatchers(input?: string | string[]): string[];
2
+ export declare function createDocumentNavigationMatchers(...paths: Array<string | undefined>): string[];
3
+ //# sourceMappingURL=matchers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"matchers.d.ts","sourceRoot":"","sources":["../src/matchers.ts"],"names":[],"mappings":"AAAA,wBAAgB,iBAAiB,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,MAAM,EAAE,CAMrE;AAED,wBAAgB,gCAAgC,CAAC,GAAG,KAAK,EAAE,KAAK,CAAC,MAAM,GAAG,SAAS,CAAC,GAAG,MAAM,EAAE,CAmB9F"}
@@ -0,0 +1,22 @@
1
+ export function normalizeMatchers(input) {
2
+ if (!input) {
3
+ return [];
4
+ }
5
+ return Array.isArray(input) ? input : [input];
6
+ }
7
+ export function createDocumentNavigationMatchers(...paths) {
8
+ const seen = new Set();
9
+ const matchers = [];
10
+ for (const path of paths) {
11
+ if (!path) {
12
+ continue;
13
+ }
14
+ const matcher = path.endsWith("(.*)") ? path : `${path}(.*)`;
15
+ if (seen.has(matcher)) {
16
+ continue;
17
+ }
18
+ seen.add(matcher);
19
+ matchers.push(matcher);
20
+ }
21
+ return matchers;
22
+ }
package/dist/url.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ export interface ResolveCallbackSettingsInput {
2
+ callbackUrl?: string;
3
+ callbackPath?: string;
4
+ defaultPath: string;
5
+ label: string;
6
+ }
7
+ export declare function getOrigin(request: Request, configuredBaseUrl?: string): string;
8
+ export declare function getReturnTo(rawValue: string | null | undefined, fallback?: string): string;
9
+ export declare function toAbsoluteUrl(pathOrUrl: string, request: Request, configuredBaseUrl?: string): URL;
10
+ export declare function withSearchParams(url: URL, params: Record<string, string | null | undefined>): URL;
11
+ export declare function resolveAppPath(path: string | undefined, label: string): string | undefined;
12
+ export declare function resolveCallbackSettings(input: ResolveCallbackSettingsInput, configuredBaseUrl?: string): {
13
+ callbackPath: string;
14
+ getCallbackUrl: (request: Request, params?: Record<string, string | null | undefined>) => string;
15
+ };
16
+ //# sourceMappingURL=url.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"url.d.ts","sourceRoot":"","sources":["../src/url.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,4BAA4B;IAC3C,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,MAAM,CAAC;IACpB,KAAK,EAAE,MAAM,CAAC;CACf;AAED,wBAAgB,SAAS,CAAC,OAAO,EAAE,OAAO,EAAE,iBAAiB,CAAC,EAAE,MAAM,GAAG,MAAM,CAE9E;AAED,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,QAAQ,SAAM,GAAG,MAAM,CAMvF;AAED,wBAAgB,aAAa,CAC3B,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,OAAO,EAChB,iBAAiB,CAAC,EAAE,MAAM,GACzB,GAAG,CAML;AAED,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC,GAAG,GAAG,CAUjG;AAED,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAU1F;AAED,wBAAgB,uBAAuB,CACrC,KAAK,EAAE,4BAA4B,EACnC,iBAAiB,CAAC,EAAE,MAAM,GACzB;IACD,YAAY,EAAE,MAAM,CAAC;IACrB,cAAc,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC,KAAK,MAAM,CAAC;CAClG,CAkCA"}
package/dist/url.js ADDED
@@ -0,0 +1,62 @@
1
+ export function getOrigin(request, configuredBaseUrl) {
2
+ return configuredBaseUrl || new URL(request.url).origin;
3
+ }
4
+ export function getReturnTo(rawValue, fallback = "/") {
5
+ if (!rawValue || !rawValue.startsWith("/")) {
6
+ return fallback;
7
+ }
8
+ return rawValue;
9
+ }
10
+ export function toAbsoluteUrl(pathOrUrl, request, configuredBaseUrl) {
11
+ try {
12
+ return new URL(pathOrUrl);
13
+ }
14
+ catch {
15
+ return new URL(pathOrUrl, getOrigin(request, configuredBaseUrl));
16
+ }
17
+ }
18
+ export function withSearchParams(url, params) {
19
+ for (const [key, value] of Object.entries(params)) {
20
+ if (value == null || value === "") {
21
+ continue;
22
+ }
23
+ url.searchParams.set(key, value);
24
+ }
25
+ return url;
26
+ }
27
+ export function resolveAppPath(path, label) {
28
+ if (!path) {
29
+ return undefined;
30
+ }
31
+ if (!path.startsWith("/")) {
32
+ throw new Error(`${label} must be a root-relative path.`);
33
+ }
34
+ return path;
35
+ }
36
+ export function resolveCallbackSettings(input, configuredBaseUrl) {
37
+ if (input.callbackUrl) {
38
+ let parsedUrl;
39
+ try {
40
+ parsedUrl = new URL(input.callbackUrl);
41
+ }
42
+ catch {
43
+ throw new Error(`${input.label} callbackUrl must be an absolute URL.`);
44
+ }
45
+ if (input.callbackPath && input.callbackPath !== parsedUrl.pathname) {
46
+ throw new Error(`${input.label} callbackUrl pathname must match callbackPath when both are provided.`);
47
+ }
48
+ return {
49
+ callbackPath: input.callbackPath ?? parsedUrl.pathname,
50
+ getCallbackUrl(_request, params = {}) {
51
+ return withSearchParams(new URL(parsedUrl.toString()), params).toString();
52
+ },
53
+ };
54
+ }
55
+ const callbackPath = input.callbackPath ?? input.defaultPath;
56
+ return {
57
+ callbackPath,
58
+ getCallbackUrl(request, params = {}) {
59
+ return withSearchParams(new URL(callbackPath, getOrigin(request, configuredBaseUrl)), params).toString();
60
+ },
61
+ };
62
+ }
@@ -0,0 +1,43 @@
1
+ import type { FarmIntegrationHandlerContext } from "@farm.js/core";
2
+ export interface FarmWebhookEvent<TProvider extends string = string, TType extends string = string, TData = unknown, TRaw = unknown> {
3
+ provider: TProvider;
4
+ id: string;
5
+ type: TType;
6
+ data: TData;
7
+ raw: TRaw;
8
+ }
9
+ export interface FarmWebhookContext {
10
+ request: Request;
11
+ route: FarmIntegrationHandlerContext;
12
+ rawBody: string;
13
+ headers: Headers;
14
+ webhook: {
15
+ name: string;
16
+ path: string;
17
+ };
18
+ }
19
+ export interface FarmWebhookDefinition<TEvent extends FarmWebhookEvent = FarmWebhookEvent> {
20
+ path?: string;
21
+ secret?: string;
22
+ onEvent?: (event: TEvent, context: FarmWebhookContext) => void | Promise<void>;
23
+ onError?: (error: unknown, context: FarmWebhookContext) => Response | void | Promise<Response | void>;
24
+ }
25
+ export type FarmWebhookConfig<TEvent extends FarmWebhookEvent = FarmWebhookEvent> = FarmWebhookDefinition<TEvent> | Record<string, FarmWebhookDefinition<TEvent>>;
26
+ export interface FarmNormalizedWebhookDefinition<TEvent extends FarmWebhookEvent = FarmWebhookEvent> extends FarmWebhookDefinition<TEvent> {
27
+ name: string;
28
+ path: string;
29
+ }
30
+ export interface FarmWebhookAckResult {
31
+ received: true;
32
+ provider: string;
33
+ webhook: string;
34
+ eventId: string;
35
+ type: string;
36
+ }
37
+ export declare function normalizeWebhookConfig<TEvent extends FarmWebhookEvent = FarmWebhookEvent>(input: {
38
+ webhooks?: FarmWebhookConfig<TEvent>;
39
+ defaultName: string;
40
+ defaultPath: string;
41
+ defaultSecret?: string;
42
+ }): FarmNormalizedWebhookDefinition<TEvent>[];
43
+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GAC7B,MAAM,CAAC,MAAM,EAAE,qBAAqB,CAAC,MAAM,CAAC,CAAC,CAAC;AAElD,MAAM,WAAW,+BAA+B,CAC9C,MAAM,SAAS,gBAAgB,GAAG,gBAAgB,CAClD,SAAQ,qBAAqB,CAAC,MAAM,CAAC;IACrC,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,oBAAoB;IACnC,QAAQ,EAAE,IAAI,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;CACd;AAeD,wBAAgB,sBAAsB,CAAC,MAAM,SAAS,gBAAgB,GAAG,gBAAgB,EAAE,KAAK,EAAE;IAChG,QAAQ,CAAC,EAAE,iBAAiB,CAAC,MAAM,CAAC,CAAC;IACrC,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB,GAAG,+BAA+B,CAAC,MAAM,CAAC,EAAE,CAgD5C"}
@@ -0,0 +1,46 @@
1
+ function isWebhookDefinition(value) {
2
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
3
+ return false;
4
+ }
5
+ return "path" in value || "secret" in value || "onEvent" in value || "onError" in value;
6
+ }
7
+ export function normalizeWebhookConfig(input) {
8
+ const { webhooks, defaultName, defaultPath, defaultSecret } = input;
9
+ if (!webhooks) {
10
+ return [];
11
+ }
12
+ const normalized = isWebhookDefinition(webhooks)
13
+ ? [
14
+ {
15
+ ...webhooks,
16
+ name: defaultName,
17
+ path: webhooks.path ?? defaultPath,
18
+ secret: webhooks.secret ?? defaultSecret,
19
+ },
20
+ ]
21
+ : Object.entries(webhooks).map(([name, definition]) => {
22
+ if (!definition || typeof definition !== "object" || Array.isArray(definition)) {
23
+ throw new Error(`Webhook "${name}" must be configured with an object.`);
24
+ }
25
+ if (!definition.path || !definition.path.trim()) {
26
+ throw new Error(`Webhook "${name}" requires an explicit path when multiple webhooks are configured.`);
27
+ }
28
+ return {
29
+ ...definition,
30
+ name,
31
+ path: definition.path,
32
+ secret: definition.secret ?? defaultSecret,
33
+ };
34
+ });
35
+ const seenPaths = new Set();
36
+ for (const definition of normalized) {
37
+ if (!definition.path.trim()) {
38
+ throw new Error(`Webhook "${definition.name}" requires a non-empty path.`);
39
+ }
40
+ if (seenPaths.has(definition.path)) {
41
+ throw new Error(`Webhook path "${definition.path}" is duplicated in the integration config.`);
42
+ }
43
+ seenPaths.add(definition.path);
44
+ }
45
+ return normalized;
46
+ }
package/package.json ADDED
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "@farm.js/integration-utils",
3
+ "version": "0.1.0-beta.0",
4
+ "description": "Shared integration utilities for Farm.js",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/farming-labs/farm.js",
9
+ "directory": "packages/farm-integration-utils"
10
+ },
11
+ "files": [
12
+ "dist"
13
+ ],
14
+ "type": "module",
15
+ "main": "./dist/index.js",
16
+ "module": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.js"
22
+ },
23
+ "./config": {
24
+ "types": "./dist/config.d.ts",
25
+ "import": "./dist/config.js"
26
+ },
27
+ "./cookies": {
28
+ "types": "./dist/cookies.d.ts",
29
+ "import": "./dist/cookies.js"
30
+ },
31
+ "./html": {
32
+ "types": "./dist/html.d.ts",
33
+ "import": "./dist/html.js"
34
+ },
35
+ "./integration": {
36
+ "types": "./dist/integration.d.ts",
37
+ "import": "./dist/integration.js"
38
+ },
39
+ "./matchers": {
40
+ "types": "./dist/matchers.d.ts",
41
+ "import": "./dist/matchers.js"
42
+ },
43
+ "./url": {
44
+ "types": "./dist/url.d.ts",
45
+ "import": "./dist/url.js"
46
+ },
47
+ "./webhooks": {
48
+ "types": "./dist/webhooks.d.ts",
49
+ "import": "./dist/webhooks.js"
50
+ }
51
+ },
52
+ "publishConfig": {
53
+ "access": "public"
54
+ },
55
+ "dependencies": {
56
+ "@farm.js/core": "0.1.0-beta.0"
57
+ },
58
+ "scripts": {
59
+ "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc",
60
+ "dev": "tsc --watch",
61
+ "type-check": "tsc --noEmit",
62
+ "test": "echo 'No tests in this package'"
63
+ }
64
+ }