@tailor-platform/sdk 0.15.1 → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # @tailor-platform/sdk
2
2
 
3
+ ## 0.16.1
4
+
5
+ ### Patch Changes
6
+
7
+ - [#160](https://github.com/tailor-platform/sdk/pull/160) [`1406523`](https://github.com/tailor-platform/sdk/commit/14065237e5f0b05cf898c0fff196e1eb599fb96f) Thanks [@toiroakr](https://github.com/toiroakr)! - fix: correctly determine create/update for workflow job functions
8
+
9
+ Previously, the SDK used `hasExistingWorkflows` (based on workflow updates) to decide whether to use `createWorkflowJobFunction` or `updateWorkflowJobFunction`. This caused errors when renaming job functions, as renamed jobs were incorrectly sent to the update API which requires the job to already exist.
10
+
11
+ Now the SDK fetches the actual list of existing job function names via `listWorkflowJobFunctions` API and correctly uses:
12
+ - `createWorkflowJobFunction` for new job names (including renamed jobs)
13
+ - `updateWorkflowJobFunction` for existing job names
14
+
15
+ ## 0.16.0
16
+
17
+ ### Minor Changes
18
+
19
+ - [#157](https://github.com/tailor-platform/sdk/pull/157) [`0677519`](https://github.com/tailor-platform/sdk/commit/06775196274dc451b60e675a2859160e2a98eae1) Thanks [@toiroakr](https://github.com/toiroakr)! - fix!: rename body to requestBody in webhook executor
20
+
3
21
  ## 0.15.1
4
22
 
5
23
  ### Patch Changes
package/README.md CHANGED
@@ -10,3 +10,4 @@ You can also view the documentation on [our website](https://docs.tailor.tech/re
10
10
  - [App Configuration](./docs/configuration.md)
11
11
  - [Core Concepts](./docs/core-concepts.md)
12
12
  - [CLI Reference](./docs/cli-reference.md)
13
+ - [Testing Guide](./docs/testing.md)
@@ -1,6 +1,6 @@
1
1
  /// <reference path="./../user-defined.d.ts" />
2
2
 
3
- import { AppConfig, CodeGeneratorBase, Executor, Generator, IdProviderConfig, OAuth2Client, Resolver, TailorDBTypeConfig } from "../types-Ct3a5JOo.mjs";
3
+ import { AppConfig, CodeGeneratorBase, Executor, Generator, IdProviderConfig, OAuth2Client, Resolver, TailorDBTypeConfig } from "../types-DGKSzhtb.mjs";
4
4
  import "citty";
5
5
  import { z } from "zod";
6
6
  import "@bufbuild/protobuf/wkt";
package/dist/cli/api.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { apply, generate, generateUserTypes, loadAccessToken, loadConfig, loadWorkspaceId, machineUserList, machineUserToken, oauth2ClientGet, oauth2ClientList, remove, show, workflowExecutionGet, workflowExecutionsList, workflowGet, workflowList, workflowResume, workflowStart, workspaceCreate, workspaceDelete, workspaceList } from "../resume-DJfAvxVb.mjs";
2
- import "../job-Dx7eROGy.mjs";
1
+ import { apply, generate, generateUserTypes, loadAccessToken, loadConfig, loadWorkspaceId, machineUserList, machineUserToken, oauth2ClientGet, oauth2ClientList, remove, show, workflowExecutionGet, workflowExecutionsList, workflowGet, workflowList, workflowResume, workflowStart, workspaceCreate, workspaceDelete, workspaceList } from "../resume-DvbIclRU.mjs";
2
+ import "../job-CL8myeqs.mjs";
3
3
  import { register } from "node:module";
4
4
 
5
5
  //#region src/cli/api.ts
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { PATScope, applyCommand, commonArgs, createCommand, deleteCommand, executionsCommand, fetchAll, fetchLatestToken, fetchUserInfo, formatArgs, generateCommand, getCommand, getCommand$1, initOAuth2Client, initOperatorClient, listCommand as listCommand$1, listCommand$1 as listCommand$6, listCommand$2 as listCommand$7, listCommand$3 as listCommand, loadAccessToken, loadConfig, loadWorkspaceId, parseFormat, printWithFormat, readPackageJson, readPlatformConfig, removeCommand, resumeCommand, showCommand, startCommand, tokenCommand, withCommonArgs, writePlatformConfig } from "../resume-DJfAvxVb.mjs";
3
- import "../job-Dx7eROGy.mjs";
2
+ import { PATScope, applyCommand, commonArgs, createCommand, deleteCommand, executionsCommand, fetchAll, fetchLatestToken, fetchUserInfo, formatArgs, generateCommand, getCommand, getCommand$1, initOAuth2Client, initOperatorClient, listCommand as listCommand$1, listCommand$1 as listCommand$6, listCommand$2 as listCommand$7, listCommand$3 as listCommand, loadAccessToken, loadConfig, loadWorkspaceId, parseFormat, printWithFormat, readPackageJson, readPlatformConfig, removeCommand, resumeCommand, showCommand, startCommand, tokenCommand, withCommonArgs, writePlatformConfig } from "../resume-DvbIclRU.mjs";
3
+ import "../job-CL8myeqs.mjs";
4
4
  import { register } from "node:module";
5
5
  import { defineCommand, runCommand, runMain } from "citty";
6
6
  import { z } from "zod";
@@ -1,5 +1,5 @@
1
1
  /// <reference path="./../user-defined.d.ts" />
2
2
 
3
- import { AttributeList, AttributeMap, AuthConfig, AuthExternalConfig, AuthInvoker, AuthOwnConfig, AuthServiceInput, BuiltinIdP, ExecutorServiceConfig, ExecutorServiceInput, IDToken, IdPConfig, IdPExternalConfig, IdProviderConfig, OAuth2Client, OAuth2ClientGrantType, OIDC, PermissionCondition, QueryType, Resolver, ResolverExternalConfig, ResolverServiceConfig, ResolverServiceInput, SAML, SCIMAttribute, SCIMAttributeMapping, SCIMAttributeType, SCIMAuthorization, SCIMConfig, SCIMResource, StaticWebsiteConfig, TailorDBField, TailorDBInstance, TailorDBType, TailorField, TailorTypeGqlPermission, TailorTypePermission, TailorUser, TenantProviderConfig, UserAttributeKey, UserAttributeListKey, UserAttributeMap, UsernameFieldKey, ValueOperand, WorkflowServiceConfig, WorkflowServiceInput, db, defineAuth, defineConfig, defineGenerators, defineIdp, defineStaticWebSite, unauthenticatedTailorUser, unsafeAllowAllGqlPermission, unsafeAllowAllTypePermission } from "../types-Ct3a5JOo.mjs";
4
- import { Env, FunctionOperation, GqlOperation, IncomingWebhookArgs, IncomingWebhookRequest, IncomingWebhookTrigger, Operation, RecordCreatedArgs, RecordDeletedArgs, RecordTrigger, RecordUpdatedArgs, ResolverExecutedArgs, ResolverExecutedTrigger, ScheduleTrigger, Trigger, WORKFLOW_JOB_BRAND, WebhookOperation, Workflow, WorkflowConfig, WorkflowJob, WorkflowJobContext, WorkflowJobInput, WorkflowJobOutput, createExecutor, createResolver, createWorkflow, createWorkflowJob, incomingWebhookTrigger, infer, output, recordCreatedTrigger, recordDeletedTrigger, recordUpdatedTrigger, resolverExecutedTrigger, scheduleTrigger, t } from "../index-Bv27MRk4.mjs";
3
+ import { AttributeList, AttributeMap, AuthConfig, AuthExternalConfig, AuthInvoker, AuthOwnConfig, AuthServiceInput, BuiltinIdP, ExecutorServiceConfig, ExecutorServiceInput, IDToken, IdPConfig, IdPExternalConfig, IdProviderConfig, OAuth2Client, OAuth2ClientGrantType, OIDC, PermissionCondition, QueryType, Resolver, ResolverExternalConfig, ResolverServiceConfig, ResolverServiceInput, SAML, SCIMAttribute, SCIMAttributeMapping, SCIMAttributeType, SCIMAuthorization, SCIMConfig, SCIMResource, StaticWebsiteConfig, TailorDBField, TailorDBInstance, TailorDBType, TailorField, TailorTypeGqlPermission, TailorTypePermission, TailorUser, TenantProviderConfig, UserAttributeKey, UserAttributeListKey, UserAttributeMap, UsernameFieldKey, ValueOperand, WorkflowServiceConfig, WorkflowServiceInput, db, defineAuth, defineConfig, defineGenerators, defineIdp, defineStaticWebSite, unauthenticatedTailorUser, unsafeAllowAllGqlPermission, unsafeAllowAllTypePermission } from "../types-DGKSzhtb.mjs";
4
+ import { Env, FunctionOperation, GqlOperation, IncomingWebhookArgs, IncomingWebhookRequest, IncomingWebhookTrigger, Operation, RecordCreatedArgs, RecordDeletedArgs, RecordTrigger, RecordUpdatedArgs, ResolverExecutedArgs, ResolverExecutedTrigger, ScheduleTrigger, Trigger, WORKFLOW_JOB_BRAND, WebhookOperation, Workflow, WorkflowConfig, WorkflowJob, WorkflowJobContext, WorkflowJobInput, WorkflowJobOutput, createExecutor, createResolver, createWorkflow, createWorkflowJob, incomingWebhookTrigger, infer, output, recordCreatedTrigger, recordDeletedTrigger, recordUpdatedTrigger, resolverExecutedTrigger, scheduleTrigger, t } from "../index-BcDejW72.mjs";
5
5
  export { AttributeList, AttributeMap, AuthConfig, AuthExternalConfig, AuthInvoker, AuthOwnConfig, AuthServiceInput, BuiltinIdP, Env, ExecutorServiceConfig, ExecutorServiceInput, FunctionOperation, GqlOperation, IDToken, IdPConfig, IdPExternalConfig, IdProviderConfig, IncomingWebhookArgs, IncomingWebhookRequest, IncomingWebhookTrigger, OAuth2Client, OAuth2ClientGrantType, OIDC, Operation, PermissionCondition, QueryType, RecordCreatedArgs, RecordDeletedArgs, RecordTrigger, RecordUpdatedArgs, Resolver, ResolverExecutedArgs, ResolverExecutedTrigger, ResolverExternalConfig, ResolverServiceConfig, ResolverServiceInput, SAML, SCIMAttribute, SCIMAttributeMapping, SCIMAttributeType, SCIMAuthorization, SCIMConfig, SCIMResource, ScheduleTrigger, StaticWebsiteConfig, TailorDBField, TailorDBInstance, TailorDBType, TailorField, TailorTypeGqlPermission, TailorTypePermission, TailorUser, TenantProviderConfig, Trigger, UserAttributeKey, UserAttributeListKey, UserAttributeMap, UsernameFieldKey, ValueOperand, WORKFLOW_JOB_BRAND, WebhookOperation, Workflow, WorkflowConfig, WorkflowJob, WorkflowJobContext, WorkflowJobInput, WorkflowJobOutput, WorkflowServiceConfig, WorkflowServiceInput, createExecutor, createResolver, createWorkflow, createWorkflowJob, db, defineAuth, defineConfig, defineGenerators, defineIdp, defineStaticWebSite, incomingWebhookTrigger, infer, output, recordCreatedTrigger, recordDeletedTrigger, recordUpdatedTrigger, resolverExecutedTrigger, scheduleTrigger, t, unauthenticatedTailorUser, unsafeAllowAllGqlPermission, unsafeAllowAllTypePermission };
@@ -1,4 +1,4 @@
1
- import { TailorField, WORKFLOW_JOB_BRAND, createWorkflowJob, db, defineAuth, defineConfig, defineGenerators, t as t$1, unauthenticatedTailorUser, unsafeAllowAllGqlPermission, unsafeAllowAllTypePermission } from "../job-Dx7eROGy.mjs";
1
+ import { TailorField, WORKFLOW_JOB_BRAND, createWorkflowJob, db, defineAuth, defineConfig, defineGenerators, t as t$1, unauthenticatedTailorUser, unsafeAllowAllGqlPermission, unsafeAllowAllTypePermission } from "../job-CL8myeqs.mjs";
2
2
 
3
3
  //#region src/configure/services/resolver/resolver.ts
4
4
  function createResolver(config) {
@@ -1,6 +1,6 @@
1
1
  /// <reference path="./user-defined.d.ts" />
2
2
 
3
- import { AllowedValues, AllowedValuesOutput, ArrayFieldOutput, AuthInvoker, ExecutorInput, FieldMetadata, FieldOptions, FieldOutput, FunctionOperation, GqlOperation, IncomingWebhookTrigger as IncomingWebhookTrigger$1, InferFieldsOutput, JsonCompatible, RecordTrigger as RecordTrigger$1, ResolverExecutedTrigger as ResolverExecutedTrigger$1, ResolverInput, ScheduleTriggerInput, TailorDBType, TailorField, TailorUser, WebhookOperation, output as output$1 } from "./types-Ct3a5JOo.mjs";
3
+ import { AllowedValues, AllowedValuesOutput, ArrayFieldOutput, AuthInvoker, ExecutorInput, FieldMetadata, FieldOptions, FieldOutput, FunctionOperation, GqlOperation, IncomingWebhookTrigger as IncomingWebhookTrigger$1, InferFieldsOutput, JsonCompatible, RecordTrigger as RecordTrigger$1, ResolverExecutedTrigger as ResolverExecutedTrigger$1, ResolverInput, ScheduleTriggerInput, TailorDBType, TailorField, TailorUser, WebhookOperation, output as output$1 } from "./types-DGKSzhtb.mjs";
4
4
  import { EmptyObject, JsonPrimitive, Jsonifiable, Jsonify } from "type-fest";
5
5
  import { Client } from "@urql/core";
6
6
  import { StandardCRON } from "ts-cron-validator";
@@ -46,9 +46,9 @@ type GqlOperation$1<Args> = Omit<GqlOperation, "query" | "variables"> & {
46
46
  variables?: (args: Args) => UrqlOperationArgs[1];
47
47
  };
48
48
  type RequestHeader = "A-IM" | "Accept" | "Accept-Additions" | "Accept-CH" | "Accept-Charset" | "Accept-Datetime" | "Accept-Encoding" | "Accept-Features" | "Accept-Language" | "Accept-Patch" | "Accept-Post" | "Accept-Ranges" | "Accept-Signature" | "Access-Control" | "Access-Control-Allow-Credentials" | "Access-Control-Allow-Headers" | "Access-Control-Allow-Methods" | "Access-Control-Allow-Origin" | "Access-Control-Expose-Headers" | "Access-Control-Max-Age" | "Access-Control-Request-Headers" | "Access-Control-Request-Method" | "Age" | "Allow" | "ALPN" | "Alt-Svc" | "Alt-Used" | "Alternates" | "AMP-Cache-Transform" | "Apply-To-Redirect-Ref" | "Authentication-Control" | "Authentication-Info" | "Authorization" | "Available-Dictionary" | "C-Ext" | "C-Man" | "C-Opt" | "C-PEP" | "C-PEP-Info" | "Cache-Control" | "Cache-Status" | "Cal-Managed-ID" | "CalDAV-Timezones" | "Capsule-Protocol" | "CDN-Cache-Control" | "CDN-Loop" | "Cert-Not-After" | "Cert-Not-Before" | "Clear-Site-Data" | "Client-Cert" | "Client-Cert-Chain" | "Close" | "CMCD-Object" | "CMCD-Request" | "CMCD-Session" | "CMCD-Status" | "CMSD-Dynamic" | "CMSD-Static" | "Concealed-Auth-Export" | "Configuration-Context" | "Connection" | "Content-Base" | "Content-Digest" | "Content-Disposition" | "Content-Encoding" | "Content-ID" | "Content-Language" | "Content-Length" | "Content-Location" | "Content-MD5" | "Content-Range" | "Content-Script-Type" | "Content-Security-Policy" | "Content-Security-Policy-Report-Only" | "Content-Style-Type" | "Content-Type" | "Content-Version" | "Cookie" | "Cookie2" | "Cross-Origin-Embedder-Policy" | "Cross-Origin-Embedder-Policy-Report-Only" | "Cross-Origin-Opener-Policy" | "Cross-Origin-Opener-Policy-Report-Only" | "Cross-Origin-Resource-Policy" | "CTA-Common-Access-Token" | "DASL" | "Date" | "DAV" | "Default-Style" | "Delta-Base" | "Deprecation" | "Depth" | "Derived-From" | "Destination" | "Differential-ID" | "Dictionary-ID" | "Digest" | "DPoP" | "DPoP-Nonce" | "Early-Data" | "EDIINT-Features" | "ETag" | "Expect" | "Expect-CT" | "Expires" | "Ext" | "Forwarded" | "From" | "GetProfile" | "Hobareg" | "Host" | "HTTP2-Settings" | "If" | "If-Match" | "If-Modified-Since" | "If-None-Match" | "If-Range" | "If-Schedule-Tag-Match" | "If-Unmodified-Since" | "IM" | "Include-Referred-Token-Binding-ID" | "Isolation" | "Keep-Alive" | "Label" | "Last-Event-ID" | "Last-Modified" | "Link" | "Link-Template" | "Location" | "Lock-Token" | "Man" | "Max-Forwards" | "Memento-Datetime" | "Meter" | "Method-Check" | "Method-Check-Expires" | "MIME-Version" | "Negotiate" | "NEL" | "OData-EntityId" | "OData-Isolation" | "OData-MaxVersion" | "OData-Version" | "Opt" | "Optional-WWW-Authenticate" | "Ordering-Type" | "Origin" | "Origin-Agent-Cluster" | "OSCORE" | "OSLC-Core-Version" | "Overwrite" | "P3P" | "PEP" | "PEP-Info" | "Permissions-Policy" | "PICS-Label" | "Ping-From" | "Ping-To" | "Position" | "Pragma" | "Prefer" | "Preference-Applied" | "Priority" | "ProfileObject" | "Protocol" | "Protocol-Info" | "Protocol-Query" | "Protocol-Request" | "Proxy-Authenticate" | "Proxy-Authentication-Info" | "Proxy-Authorization" | "Proxy-Features" | "Proxy-Instruction" | "Proxy-Status" | "Public" | "Public-Key-Pins" | "Public-Key-Pins-Report-Only" | "Range" | "Redirect-Ref" | "Referer" | "Referer-Root" | "Referrer-Policy" | "Refresh" | "Repeatability-Client-ID" | "Repeatability-First-Sent" | "Repeatability-Request-ID" | "Repeatability-Result" | "Replay-Nonce" | "Reporting-Endpoints" | "Repr-Digest" | "Retry-After" | "Safe" | "Schedule-Reply" | "Schedule-Tag" | "Sec-GPC" | "Sec-Purpose" | "Sec-Token-Binding" | "Sec-WebSocket-Accept" | "Sec-WebSocket-Extensions" | "Sec-WebSocket-Key" | "Sec-WebSocket-Protocol" | "Sec-WebSocket-Version" | "Security-Scheme" | "Server" | "Server-Timing" | "Set-Cookie" | "Set-Cookie2" | "SetProfile" | "Signature" | "Signature-Input" | "SLUG" | "SoapAction" | "Status-URI" | "Strict-Transport-Security" | "Sunset" | "Surrogate-Capability" | "Surrogate-Control" | "TCN" | "TE" | "Timeout" | "Timing-Allow-Origin" | "Topic" | "Traceparent" | "Tracestate" | "Trailer" | "Transfer-Encoding" | "TTL" | "Upgrade" | "Urgency" | "URI" | "Use-As-Dictionary" | "User-Agent" | "Variant-Vary" | "Vary" | "Via" | "Want-Content-Digest" | "Want-Digest" | "Want-Repr-Digest" | "Warning" | "WWW-Authenticate" | "X-Content-Type-Options" | "X-Frame-Options" | (string & {});
49
- type WebhookOperation$1<Args> = Omit<WebhookOperation, "url" | "body" | "headers"> & {
49
+ type WebhookOperation$1<Args> = Omit<WebhookOperation, "url" | "requestBody" | "headers"> & {
50
50
  url: (args: Args) => string;
51
- body?: (args: Args) => Record<string, unknown>;
51
+ requestBody?: (args: Args) => Record<string, unknown>;
52
52
  headers?: { [key in RequestHeader]?: string | {
53
53
  vault: string;
54
54
  key: string;
@@ -322,4 +322,4 @@ declare namespace t {
322
322
  }
323
323
  //#endregion
324
324
  export { type Env, FunctionOperation$1 as FunctionOperation, GqlOperation$1 as GqlOperation, IncomingWebhookArgs, IncomingWebhookRequest, IncomingWebhookTrigger, Operation, RecordCreatedArgs, RecordDeletedArgs, RecordTrigger, RecordUpdatedArgs, ResolverExecutedArgs, ResolverExecutedTrigger, ScheduleTrigger, Trigger, WORKFLOW_JOB_BRAND, WebhookOperation$1 as WebhookOperation, Workflow, WorkflowConfig, WorkflowJob, WorkflowJobContext, WorkflowJobInput, WorkflowJobOutput, createExecutor, createResolver, createWorkflow, createWorkflowJob, incomingWebhookTrigger, infer, output, recordCreatedTrigger, recordDeletedTrigger, recordUpdatedTrigger, resolverExecutedTrigger, scheduleTrigger, t };
325
- //# sourceMappingURL=index-Bv27MRk4.d.mts.map
325
+ //# sourceMappingURL=index-BcDejW72.d.mts.map
@@ -394,9 +394,22 @@ const unsafeAllowAllGqlPermission = [{
394
394
  function isRelationSelfConfig(config) {
395
395
  return config.toward.type === "self";
396
396
  }
397
- const convertFnToExpr = (fn) => {
397
+ /**
398
+ * Convert a function to a string representation.
399
+ * Handles method shorthand syntax (e.g., `create() { ... }`) by converting it to
400
+ * a function expression (e.g., `function create() { ... }`).
401
+ *
402
+ * TODO: This function should be moved to the parser module.
403
+ * The same function exists in `src/cli/apply/services/executor.ts`.
404
+ * These should be unified into a common utility in the parser layer.
405
+ */
406
+ const stringifyFunction = (fn) => {
398
407
  const src = fn.toString().trim();
399
- return `(${src.startsWith("create") || src.startsWith("update") ? `function ${src}` : src})({ value: _value, data: _data, user: ${tailorUserMap} })`;
408
+ if (/^[a-zA-Z_$][a-zA-Z0-9_$]*\s*\(/.test(src) && !src.startsWith("function") && !src.startsWith("(") && !src.includes("=>")) return `function ${src}`;
409
+ return src;
410
+ };
411
+ const convertFnToExpr = (fn) => {
412
+ return `(${stringifyFunction(fn)})({ value: _value, data: _data, user: ${tailorUserMap} })`;
400
413
  };
401
414
  var TailorDBField = class TailorDBField extends TailorField {
402
415
  _ref = void 0;
@@ -773,4 +786,4 @@ const createWorkflowJob = (config) => {
773
786
 
774
787
  //#endregion
775
788
  export { TailorField, WORKFLOW_JOB_BRAND, createWorkflowJob, db, defineAuth, defineConfig, defineGenerators, getDistDir, t, tailorUserMap, unauthenticatedTailorUser, unsafeAllowAllGqlPermission, unsafeAllowAllTypePermission };
776
- //# sourceMappingURL=job-Dx7eROGy.mjs.map
789
+ //# sourceMappingURL=job-CL8myeqs.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"job-CL8myeqs.mjs","names":["type: TailorFieldType","fields: Record<string, TailorField<any>>","issues: StandardSchemaV1.Issue[]","createField","uuid","string","bool","int","float","date","datetime","time","_enum","object","unauthenticatedTailorUser: TailorUser","conditions: PermissionCondition[]","unsafeAllowAllTypePermission: TailorTypePermission","unsafeAllowAllGqlPermission: TailorTypeGqlPermission","name: string","fields: Fields","indexes: Record<string, { fields: string[]; unique?: boolean }>","validators","description: string | undefined","fieldDef: F","distPath: string | null"],"sources":["../src/configure/types/field.ts","../src/configure/types/type.ts","../src/configure/types/user.ts","../src/configure/services/tailordb/permission.ts","../src/configure/services/tailordb/schema.ts","../src/configure/config.ts","../src/configure/services/auth/index.ts","../src/configure/services/workflow/job.ts"],"sourcesContent":["import { type EnumValue } from \"@/configure/types/types\";\n\nexport type AllowedValue = EnumValue;\n\nexport type AllowedValues = [string | EnumValue, ...(string | EnumValue)[]];\n\nexport function mapAllowedValues(values: AllowedValues): AllowedValue[] {\n return values.map((value) => {\n if (typeof value === \"string\") {\n return { value, description: \"\" };\n }\n return { ...value, description: value.description ?? \"\" };\n });\n}\n\nexport type AllowedValuesOutput<V extends AllowedValues> =\n V[number] extends infer T\n ? T extends string\n ? T\n : T extends { value: infer K }\n ? K\n : never\n : never;\n","import {\n type AllowedValues,\n type AllowedValuesOutput,\n mapAllowedValues,\n} from \"./field\";\nimport {\n type TailorFieldType,\n type TailorToTs,\n type FieldMetadata,\n type DefinedFieldMetadata,\n type FieldOptions,\n type FieldOutput,\n} from \"./types\";\nimport type { Prettify, InferFieldsOutput } from \"./helpers\";\nimport type { FieldValidateInput } from \"./validation\";\nimport type { TailorUser } from \"@/configure/types\";\nimport type { TailorFieldInput } from \"@/parser/service/resolver/types\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nconst regex = {\n uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,\n date: /^(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})$/,\n time: /^(?<hour>\\d{2}):(?<minute>\\d{2})$/,\n datetime:\n /^(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})T(?<hour>\\d{2}):(?<minute>\\d{2}):(?<second>\\d{2})(.(?<millisec>\\d{3}))?Z$/,\n} as const;\n\nexport class TailorField<\n const Defined extends DefinedFieldMetadata = DefinedFieldMetadata,\n const Output = any,\n M extends FieldMetadata = FieldMetadata,\n> implements TailorFieldInput {\n protected _metadata: M;\n public readonly _defined: Defined = undefined as unknown as Defined;\n public readonly _output = undefined as Output;\n\n get metadata() {\n return { ...this._metadata };\n }\n\n protected constructor(\n public readonly type: TailorFieldType,\n options?: FieldOptions,\n public readonly fields: Record<string, TailorField<any>> = {},\n values?: AllowedValues,\n ) {\n this._metadata = { required: true } as M;\n if (options) {\n if (options.optional === true) {\n this._metadata.required = false;\n }\n if (options.array === true) {\n this._metadata.array = true;\n }\n }\n if (values) {\n this._metadata.allowedValues = mapAllowedValues(values);\n }\n }\n\n static create<\n const TType extends TailorFieldType,\n const TOptions extends FieldOptions,\n const OutputBase = TailorToTs[TType],\n >(\n type: TType,\n options?: TOptions,\n fields?: Record<string, TailorField<any>>,\n values?: AllowedValues,\n ) {\n return new TailorField<\n { type: TType; array: TOptions extends { array: true } ? true : false },\n FieldOutput<OutputBase, TOptions>\n >(type, options, fields, values);\n }\n\n description<CurrentDefined extends Defined>(\n this: CurrentDefined extends { description: unknown }\n ? never\n : TailorField<CurrentDefined, Output>,\n description: string,\n ) {\n this._metadata.description = description;\n return this as TailorField<\n Prettify<CurrentDefined & { description: true }>,\n Output\n >;\n }\n\n typeName<CurrentDefined extends Defined>(\n this: CurrentDefined extends { typeName: unknown }\n ? never\n : CurrentDefined extends { type: \"enum\" | \"nested\" }\n ? TailorField<CurrentDefined, Output>\n : never,\n typeName: string,\n ) {\n this._metadata.typeName = typeName;\n return this as TailorField<\n Prettify<CurrentDefined & { typeName: true }>,\n Output\n >;\n }\n\n validate<CurrentDefined extends Defined>(\n this: CurrentDefined extends { validate: unknown }\n ? never\n : TailorField<CurrentDefined, Output>,\n ...validate: FieldValidateInput<Output>[]\n ) {\n this._metadata.validate = validate;\n return this as TailorField<\n Prettify<CurrentDefined & { validate: true }>,\n Output\n >;\n }\n\n /**\n * Parse and validate a value against this field's validation rules\n * Returns StandardSchema Result type with success or failure\n */\n parse(args: {\n value: any;\n data: any;\n user: TailorUser;\n }): StandardSchemaV1.Result<Output> {\n return this._parseInternal({\n value: args.value,\n data: args.data,\n user: args.user,\n pathArray: [],\n });\n }\n\n /**\n * Validate a single value (not an array element)\n * Used internally for array element validation\n * @private\n */\n private _validateValue(args: {\n value: any;\n data: any;\n user: TailorUser;\n pathArray: string[];\n }): StandardSchemaV1.Issue[] {\n const { value, data, user, pathArray } = args;\n const issues: StandardSchemaV1.Issue[] = [];\n\n // Type-specific validation\n switch (this.type) {\n case \"string\":\n if (typeof value !== \"string\") {\n issues.push({\n message: `Expected a string: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n\n case \"integer\":\n if (typeof value !== \"number\" || !Number.isInteger(value)) {\n issues.push({\n message: `Expected an integer: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n\n case \"float\":\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n issues.push({\n message: `Expected a number: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n issues.push({\n message: `Expected a boolean: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n\n case \"uuid\":\n if (typeof value !== \"string\" || !regex.uuid.test(value)) {\n issues.push({\n message: `Expected a valid UUID: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n case \"date\":\n if (typeof value !== \"string\" || !regex.date.test(value)) {\n issues.push({\n message: `Expected to match \"yyyy-MM-dd\" format: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n case \"datetime\":\n if (typeof value !== \"string\" || !regex.datetime.test(value)) {\n issues.push({\n message: `Expected to match ISO format: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n case \"time\":\n if (typeof value !== \"string\" || !regex.time.test(value)) {\n issues.push({\n message: `Expected to match \"HH:mm:ss\" format`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n case \"enum\":\n if (this.metadata.allowedValues) {\n const allowedValues = this.metadata.allowedValues.map((v) => v.value);\n if (!allowedValues.includes(value)) {\n issues.push({\n message: `Must be one of [${allowedValues.join(\", \")}]: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n }\n break;\n\n case \"nested\":\n // Validate nested object fields\n if (\n typeof value !== \"object\" ||\n value === null ||\n Array.isArray(value)\n ) {\n issues.push({\n message: `Expected an object: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n } else if (this.fields && Object.keys(this.fields).length > 0) {\n for (const [fieldName, field] of Object.entries(this.fields)) {\n const fieldValue = value?.[fieldName];\n const result = field._parseInternal({\n value: fieldValue,\n data,\n user,\n pathArray: pathArray.concat(fieldName),\n });\n if (result.issues) {\n issues.push(...result.issues);\n }\n }\n }\n break;\n }\n\n // Custom validation functions\n const validateFns = this.metadata.validate;\n if (validateFns && validateFns.length > 0) {\n for (const validateInput of validateFns) {\n const { fn, message } =\n typeof validateInput === \"function\"\n ? { fn: validateInput, message: \"Validation failed\" }\n : { fn: validateInput[0], message: validateInput[1] };\n\n if (!fn({ value, data, user })) {\n issues.push({\n message,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n }\n }\n\n return issues;\n }\n\n /**\n * Internal parse method that tracks field path for nested validation\n * @private\n */\n private _parseInternal(args: {\n value: any;\n data: any;\n user: TailorUser;\n pathArray: string[];\n }): StandardSchemaV1.Result<Output> {\n const { value, data, user, pathArray } = args;\n const issues: StandardSchemaV1.Issue[] = [];\n\n // 1. Check required/optional\n const isNullOrUndefined = value === null || value === undefined;\n if (this.metadata.required && isNullOrUndefined) {\n issues.push({\n message: \"Required field is missing\",\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n return { issues };\n }\n\n // If optional and null/undefined, skip further validation\n if (!this.metadata.required && isNullOrUndefined) {\n return { value };\n }\n\n // 2. Check array type\n if (this.metadata.array) {\n if (!Array.isArray(value)) {\n issues.push({\n message: \"Expected an array\",\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n return { issues };\n }\n\n // Validate each array element (without array flag)\n for (let i = 0; i < value.length; i++) {\n const elementValue = value[i];\n const elementPath = pathArray.concat(`[${i}]`);\n\n // Validate element with same type but without array flag\n const elementIssues = this._validateValue({\n value: elementValue,\n data,\n user,\n pathArray: elementPath,\n });\n if (elementIssues.length > 0) {\n issues.push(...elementIssues);\n }\n }\n\n if (issues.length > 0) {\n return { issues };\n }\n return { value: value as Output };\n }\n\n // 3. Type-specific validation and custom validation\n const valueIssues = this._validateValue({ value, data, user, pathArray });\n issues.push(...valueIssues);\n\n if (issues.length > 0) {\n return { issues };\n }\n\n return { value };\n }\n}\n\nconst createField = TailorField.create;\nfunction uuid<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"uuid\", options);\n}\n\nfunction string<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"string\", options);\n}\n\nfunction bool<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"boolean\", options);\n}\n\nfunction int<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"integer\", options);\n}\n\nfunction float<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"float\", options);\n}\n\nfunction date<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"date\", options);\n}\n\nfunction datetime<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"datetime\", options);\n}\n\nfunction time<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"time\", options);\n}\n\nfunction _enum<const V extends AllowedValues, const Opt extends FieldOptions>(\n values: V,\n options?: Opt,\n): TailorField<\n { type: \"enum\"; array: Opt extends { array: true } ? true : false },\n FieldOutput<AllowedValuesOutput<V>, Opt>\n> {\n return createField<\"enum\", Opt, AllowedValuesOutput<V>>(\n \"enum\",\n options,\n undefined,\n values,\n );\n}\n\nfunction object<\n const F extends Record<string, TailorField<any>>,\n const Opt extends FieldOptions,\n>(fields: F, options?: Opt) {\n const objectField = createField(\"nested\", options, fields) as TailorField<\n { type: \"nested\"; array: Opt extends { array: true } ? true : false },\n FieldOutput<InferFieldsOutput<F>, Opt>\n >;\n return objectField;\n}\n\nexport const t = {\n uuid,\n string,\n bool,\n int,\n float,\n date,\n datetime,\n time,\n enum: _enum,\n object,\n};\n","// Interfaces for module augmentation\n// Users can extend these via: declare module \"@tailor-platform/sdk\" { interface AttributeMap { ... } }\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface AttributeMap {}\nexport interface AttributeList {\n __tuple?: []; // Marker for tuple type\n}\n\nexport type InferredAttributeMap = keyof AttributeMap extends never\n ? Record<string, string | string[] | boolean | boolean[] | undefined>\n : AttributeMap;\n\nexport type InferredAttributeList = AttributeList[\"__tuple\"] extends []\n ? string[]\n : AttributeList[\"__tuple\"];\n\n/** Represents a user in the Tailor platform. */\nexport type TailorUser = {\n /**\n * The ID of the user.\n * For unauthenticated users, this will be a nil UUID.\n */\n id: string;\n /**\n * The type of the user.\n * For unauthenticated users, this will be an empty string.\n */\n type: \"user\" | \"machine_user\" | \"\";\n /** The ID of the workspace the user belongs to. */\n workspaceId: string;\n /**\n * A map of the user's attributes.\n * For unauthenticated users, this will be null.\n */\n attributes: InferredAttributeMap | null;\n /**\n * A list of the user's attributes.\n * For unauthenticated users, this will be an empty array.\n */\n attributeList: InferredAttributeList;\n};\n\n/** Represents an unauthenticated user in the Tailor platform. */\nexport const unauthenticatedTailorUser: TailorUser = {\n id: \"00000000-0000-0000-0000-000000000000\",\n type: \"\",\n workspaceId: \"00000000-0000-0000-0000-000000000000\",\n attributes: null,\n attributeList: [],\n};\n\n// Since there's naming difference between platform and sdk,\n// use this mapping in all scripts to provide variables that match sdk types.\nexport const tailorUserMap = /* js */ `{ id: user.id, type: user.type, workspaceId: user.workspace_id, attributes: user.attribute_map, attributeList: user.attributes }`;\n","import type { InferredAttributeMap } from \"../../types\";\nimport type { ValueOperand } from \"../auth\";\n\nexport interface Permissions {\n record?: StandardTailorTypePermission;\n gql?: StandardTailorTypeGqlPermission;\n}\n\nexport type TailorTypePermission<\n User extends object = InferredAttributeMap,\n Type extends object = object,\n> = {\n create: readonly ActionPermission<\"record\", User, Type, false>[];\n read: readonly ActionPermission<\"record\", User, Type, false>[];\n update: readonly ActionPermission<\"record\", User, Type, true>[];\n delete: readonly ActionPermission<\"record\", User, Type, false>[];\n};\n\nexport type StandardTailorTypePermission = {\n create: readonly StandardActionPermission<\"record\", false>[];\n read: readonly StandardActionPermission<\"record\", false>[];\n update: readonly StandardActionPermission<\"record\", true>[];\n delete: readonly StandardActionPermission<\"record\", false>[];\n};\n\ntype ActionPermission<\n Level extends \"record\" | \"gql\" = \"record\" | \"gql\",\n User extends object = InferredAttributeMap,\n Type extends object = object,\n Update extends boolean = boolean,\n> =\n | {\n conditions:\n | PermissionCondition<Level, User, Update, Type>\n | readonly PermissionCondition<Level, User, Update, Type>[];\n description?: string | undefined;\n permit?: boolean;\n }\n | readonly [\n ...PermissionCondition<Level, User, Update, Type>,\n ...([] | [boolean]),\n ] // single array condition\n | readonly [\n ...PermissionCondition<Level, User, Update, Type>[],\n ...([] | [boolean]),\n ]; // multiple array condition\n\nexport type StandardActionPermission<\n Level extends \"record\" | \"gql\" = \"record\" | \"gql\",\n Update extends boolean = boolean,\n> = {\n conditions: readonly StandardPermissionCondition<Level, Update>[];\n description?: string;\n permit: \"allow\" | \"deny\";\n};\n\nexport type TailorTypeGqlPermission<\n User extends object = InferredAttributeMap,\n Type extends object = object,\n> = readonly GqlPermissionPolicy<User, Type>[];\n\nexport type StandardTailorTypeGqlPermission =\n readonly StandardGqlPermissionPolicy[];\n\ntype GqlPermissionPolicy<\n User extends object = InferredAttributeMap,\n Type extends object = object,\n> = {\n conditions: readonly PermissionCondition<\"gql\", User, boolean, Type>[];\n actions: \"all\" | readonly GqlPermissionAction[];\n permit?: boolean;\n description?: string;\n};\n\nexport type StandardGqlPermissionPolicy = {\n conditions: readonly StandardPermissionCondition<\"gql\">[];\n actions: readonly [\"all\"] | readonly GqlPermissionAction[];\n permit: \"allow\" | \"deny\";\n description?: string;\n};\n\ntype GqlPermissionAction =\n | \"read\"\n | \"create\"\n | \"update\"\n | \"delete\"\n | \"aggregate\"\n | \"bulkUpsert\";\n\nexport type PermissionCondition<\n Level extends \"record\" | \"gql\" = \"record\" | \"gql\",\n User extends object = InferredAttributeMap,\n Update extends boolean = boolean,\n Type extends object = object,\n> = readonly [\n PermissionOperand<Level, User, Type, Update>,\n PermissionOperator,\n PermissionOperand<Level, User, Type, Update>,\n];\n\nexport type StandardPermissionCondition<\n Level extends \"record\" | \"gql\" = \"record\" | \"gql\",\n Update extends boolean = boolean,\n> = readonly [\n PermissionOperand<\n Level,\n Record<string, unknown>,\n Record<string, unknown>,\n Update\n >,\n StandardPermissionOperator,\n PermissionOperand<\n Level,\n Record<string, unknown>,\n Record<string, unknown>,\n Update\n >,\n];\n\ntype UserOperand<User extends object = InferredAttributeMap> = {\n user:\n | {\n [K in keyof User]: User[K] extends\n | string\n | string[]\n | boolean\n | boolean[]\n ? K\n : never;\n }[keyof User]\n | \"id\"\n | \"_loggedIn\";\n};\n\ntype RecordOperand<\n Type extends object,\n Update extends boolean = false,\n> = Update extends true\n ?\n | { oldRecord: (keyof Type & string) | \"id\" }\n | { newRecord: (keyof Type & string) | \"id\" }\n : { record: (keyof Type & string) | \"id\" };\n\nexport type PermissionOperand<\n Level extends \"record\" | \"gql\" = \"record\" | \"gql\",\n User extends object = InferredAttributeMap,\n Type extends object = object,\n Update extends boolean = boolean,\n> =\n | UserOperand<User>\n | ValueOperand\n | (Level extends \"record\" ? RecordOperand<Type, Update> : never);\n\ntype PermissionOperator = \"=\" | \"!=\" | \"in\" | \"not in\";\nconst operatorMap = {\n \"=\": \"eq\",\n \"!=\": \"ne\",\n in: \"in\",\n \"not in\": \"nin\",\n} as const satisfies Record<PermissionOperator, string>;\ntype StandardPermissionOperator =\n (typeof operatorMap)[keyof typeof operatorMap];\n\nfunction normalizeOperand<T extends PermissionOperand<any, any, any, any>>(\n operand: T,\n): T {\n if (typeof operand === \"object\" && \"user\" in operand) {\n return { user: { id: \"_id\" }[operand.user] ?? operand.user } as T;\n }\n return operand;\n}\n\nfunction normalizeConditions<\n Level extends \"record\" | \"gql\" = \"record\" | \"gql\",\n Update extends boolean = boolean,\n>(\n conditions: readonly PermissionCondition<Level, any, Update, any>[],\n): StandardPermissionCondition<Level, Update>[] {\n return conditions.map((cond) => {\n const [left, operator, right] = cond;\n return [\n normalizeOperand(left),\n operatorMap[operator],\n normalizeOperand(right),\n ];\n }) as StandardPermissionCondition<Level, Update>[];\n}\n\nfunction isObjectFormat(\n p: ActionPermission,\n): p is Extract<ActionPermission, { permit?: boolean }> {\n return typeof p === \"object\" && p !== null && \"conditions\" in p;\n}\n\nfunction isSingleArrayConditionFormat(\n cond: Exclude<ActionPermission, { permit?: boolean }>,\n): cond is PermissionCondition {\n return cond.length >= 2 && typeof cond[1] === \"string\"; // Check if middle element is an operator\n}\n\nexport function normalizePermission<\n User extends object = object,\n Type extends object = object,\n>(permission: TailorTypePermission<User, Type>): StandardTailorTypePermission {\n return Object.keys(permission).reduce((acc, action) => {\n (acc as any)[action] = (permission as any)[action].map((p: any) =>\n normalizeActionPermission(p),\n );\n return acc;\n }, {}) as StandardTailorTypePermission;\n}\n\nexport function normalizeGqlPermission<\n const P extends TailorTypeGqlPermission<any>,\n>(permission: P): StandardTailorTypeGqlPermission {\n return permission.map((policy) =>\n normalizeGqlPolicy(policy),\n ) as StandardTailorTypeGqlPermission;\n}\n\nfunction normalizeGqlPolicy(\n policy: GqlPermissionPolicy<any, any>,\n): StandardGqlPermissionPolicy {\n return {\n conditions: policy.conditions ? normalizeConditions(policy.conditions) : [],\n actions: policy.actions === \"all\" ? [\"all\"] : policy.actions,\n permit: policy.permit ? \"allow\" : \"deny\",\n description: policy.description,\n };\n}\nexport function normalizeActionPermission(\n permission: ActionPermission,\n): StandardActionPermission {\n // object format\n if (isObjectFormat(permission)) {\n return {\n conditions: normalizeConditions(\n isSingleArrayConditionFormat(permission.conditions)\n ? [permission.conditions]\n : permission.conditions,\n ),\n permit: permission.permit ? \"allow\" : \"deny\",\n description: permission.description,\n };\n }\n\n if (isSingleArrayConditionFormat(permission)) {\n const [op1, operator, op2, permit] = [...permission, true];\n return {\n conditions: normalizeConditions([[op1, operator, op2]]),\n permit: permit ? \"allow\" : \"deny\",\n };\n }\n\n // Array of conditions format\n const conditions: PermissionCondition[] = [];\n const conditionArray = permission;\n let conditionArrayPermit = true;\n\n for (const item of conditionArray) {\n if (typeof item === \"boolean\") {\n conditionArrayPermit = item;\n continue;\n }\n conditions.push(item as PermissionCondition);\n }\n\n return {\n conditions: normalizeConditions(conditions),\n permit: conditionArrayPermit ? \"allow\" : \"deny\",\n };\n}\n\n/**\n * Grants full record-level access without any conditions.\n *\n * Unsafe and intended only for local development, prototyping, or tests.\n * Do not use this in production environments, as it effectively disables\n * authorization checks.\n */\nexport const unsafeAllowAllTypePermission: TailorTypePermission = {\n create: [{ conditions: [], permit: true }],\n read: [{ conditions: [], permit: true }],\n update: [{ conditions: [], permit: true }],\n delete: [{ conditions: [], permit: true }],\n};\n\n/**\n * Grants full GraphQL access (all actions) without any conditions.\n *\n * Unsafe and intended only for local development, prototyping, or tests.\n * Do not use this in production environments, as it effectively disables\n * authorization checks.\n */\nexport const unsafeAllowAllGqlPermission: TailorTypeGqlPermission = [\n { conditions: [], actions: \"all\", permit: true },\n];\n","import { clone } from \"es-toolkit\";\nimport { type InferredAttributeMap, tailorUserMap } from \"@/configure/types\";\nimport {\n type AllowedValues,\n type AllowedValuesOutput,\n} from \"@/configure/types/field\";\nimport { type OperatorFieldConfig } from \"@/configure/types/operator\";\nimport { TailorField } from \"@/configure/types/type\";\nimport {\n type FieldOptions,\n type FieldOutput,\n type TailorFieldType,\n type TailorToTs,\n} from \"@/configure/types/types\";\nimport { type TailorDBTypeConfig } from \"./operator-types\";\nimport {\n type Permissions,\n type TailorTypeGqlPermission,\n type TailorTypePermission,\n normalizePermission,\n normalizeGqlPermission,\n} from \"./permission\";\nimport {\n type DBFieldMetadata,\n type DefinedDBFieldMetadata,\n type Hooks,\n type Hook,\n type SerialConfig,\n type IndexDef,\n type TypeFeatures,\n type ExcludeNestedDBFields,\n} from \"./types\";\nimport type {\n Prettify,\n output,\n InferFieldsOutput,\n} from \"@/configure/types/helpers\";\nimport type {\n FieldValidateInput,\n ValidateConfig,\n Validators,\n} from \"@/configure/types/validation\";\n\ntype RelationType =\n | \"oneToOne\"\n | \"1-1\"\n | \"manyToOne\"\n | \"n-1\"\n | \"N-1\"\n | \"keyOnly\";\n\ninterface RelationConfig<S extends RelationType, T extends TailorDBType> {\n type: S;\n toward: {\n type: T;\n as?: string;\n key?: keyof T[\"fields\"] & string;\n };\n backward?: string;\n}\n\n// Special config variant for self-referencing relations\ntype RelationSelfConfig = {\n type: RelationType;\n toward: {\n type: \"self\";\n as?: string;\n key?: string;\n };\n backward?: string;\n};\n\ninterface PendingSelfRelation {\n type: RelationType;\n as?: string;\n key: string;\n backward: string;\n}\n\nfunction isRelationSelfConfig(\n config: RelationConfig<RelationType, TailorDBType> | RelationSelfConfig,\n): config is RelationSelfConfig {\n return config.toward.type === \"self\";\n}\n\ninterface ReferenceConfig<T extends TailorDBType<any, any>> {\n type: TailorDBType<any, any>;\n key: keyof T[\"fields\"] & string;\n nameMap: [string | undefined, string];\n}\n\n/**\n * Convert a function to a string representation.\n * Handles method shorthand syntax (e.g., `create() { ... }`) by converting it to\n * a function expression (e.g., `function create() { ... }`).\n *\n * TODO: This function should be moved to the parser module.\n * The same function exists in `src/cli/apply/services/executor.ts`.\n * These should be unified into a common utility in the parser layer.\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nconst stringifyFunction = (fn: Function): string => {\n const src = fn.toString().trim();\n // Method shorthand pattern: methodName(...) { ... }\n // Needs to be converted to: function methodName(...) { ... }\n if (\n /^[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/.test(src) &&\n !src.startsWith(\"function\") &&\n !src.startsWith(\"(\") &&\n !src.includes(\"=>\")\n ) {\n return `function ${src}`;\n }\n return src;\n};\n\nconst convertFnToExpr = (\n fn: NonNullable<Hook<any, any>[\"create\"] | Hook<any, any>[\"update\"]>,\n) => {\n const normalized = stringifyFunction(fn);\n return `(${normalized})({ value: _value, data: _data, user: ${tailorUserMap} })`;\n};\n\nexport class TailorDBField<\n const Defined extends DefinedDBFieldMetadata,\n const Output,\n> extends TailorField<Defined, Output, DBFieldMetadata> {\n private _ref: ReferenceConfig<TailorDBType> | undefined = undefined;\n private _pendingSelfRelation: PendingSelfRelation | undefined = undefined;\n\n get reference(): Readonly<ReferenceConfig<TailorDBType>> | undefined {\n return clone(this._ref);\n }\n\n get metadata() {\n return { ...this._metadata };\n }\n\n get config(): OperatorFieldConfig {\n return {\n type: this.type,\n ...this._metadata,\n ...(this.type === \"nested\" && Object.keys(this.fields).length > 0\n ? {\n fields: Object.entries(this.fields).reduce(\n (acc, [key, field]) => {\n acc[key] = (field as TailorDBField<any, any>).config;\n return acc;\n },\n {} as Record<string, OperatorFieldConfig>,\n ),\n }\n : {}),\n validate: this._metadata.validate?.map((v) => {\n const { fn, message } =\n typeof v === \"function\"\n ? { fn: v, message: `failed by \\`${v.toString().trim()}\\`` }\n : { fn: v[0], message: v[1] };\n\n return {\n script: {\n expr: `(${fn.toString().trim()})({ value: _value, data: _data, user: ${tailorUserMap} })`,\n },\n errorMessage: message,\n };\n }),\n hooks: this._metadata.hooks\n ? {\n create: this._metadata.hooks.create\n ? {\n expr: convertFnToExpr(this._metadata.hooks.create),\n }\n : undefined,\n update: this._metadata.hooks.update\n ? {\n expr: convertFnToExpr(this._metadata.hooks.update),\n }\n : undefined,\n }\n : undefined,\n serial: this._metadata.serial\n ? {\n start: this._metadata.serial.start,\n maxValue: this._metadata.serial.maxValue,\n format:\n \"format\" in this._metadata.serial\n ? this._metadata.serial.format\n : undefined,\n }\n : undefined,\n };\n }\n\n private constructor(\n type: TailorFieldType,\n options?: FieldOptions,\n fields?: Record<string, TailorDBField<any, any>>,\n values?: AllowedValues,\n ) {\n super(type, options, fields, values);\n }\n\n static create<\n const T extends TailorFieldType,\n const TOptions extends FieldOptions,\n const OutputBase = TailorToTs[T],\n >(\n type: T,\n options?: TOptions,\n fields?: Record<string, TailorDBField<any, any>>,\n values?: AllowedValues,\n ) {\n return new TailorDBField<\n { type: T; array: TOptions extends { array: true } ? true : false },\n FieldOutput<OutputBase, TOptions>\n >(type, options, fields, values);\n }\n\n description<CurrentDefined extends Defined>(\n this: CurrentDefined extends { description: unknown }\n ? never\n : TailorField<CurrentDefined, Output>,\n description: string,\n ): TailorDBField<Prettify<CurrentDefined & { description: true }>, Output> {\n return super.description(description) as any;\n }\n\n relation<\n S extends RelationType,\n T extends TailorDBType<any, any>,\n CurrentDefined extends Defined,\n >(\n this: CurrentDefined extends { relation: unknown }\n ? never\n : TailorDBField<CurrentDefined, Output>,\n config: RelationConfig<S, T>,\n ): TailorDBField<\n S extends \"oneToOne\" | \"1-1\"\n ? Prettify<CurrentDefined & { unique: true; index: true; relation: true }>\n : Prettify<CurrentDefined & { index: true; relation: true }>,\n Output\n >;\n\n // Overload: self-referencing variant\n relation<S extends RelationSelfConfig, CurrentDefined extends Defined>(\n this: CurrentDefined extends { relation: unknown }\n ? never\n : TailorDBField<CurrentDefined, Output>,\n config: S,\n ): TailorDBField<\n S[\"type\"] extends \"oneToOne\" | \"1-1\"\n ? Prettify<CurrentDefined & { unique: true; index: true; relation: true }>\n : Prettify<CurrentDefined & { index: true; relation: true }>,\n Output\n >;\n\n // Implementation\n relation<CurrentDefined extends Defined>(\n this: CurrentDefined extends { relation: unknown }\n ? never\n : TailorDBField<CurrentDefined, Output>,\n config: RelationConfig<RelationType, TailorDBType> | RelationSelfConfig,\n ): TailorDBField<DefinedDBFieldMetadata, Output> {\n this._metadata.index = true;\n this._metadata.foreignKey = true;\n this._metadata.unique = [\"oneToOne\", \"1-1\"].includes(config.type);\n\n const key = config.toward.key ?? \"id\";\n const backward = config.backward ?? \"\";\n\n if (isRelationSelfConfig(config)) {\n // Defer resolving the self reference until the type is constructed\n this._pendingSelfRelation = {\n type: config.type,\n as: config.toward.as,\n key,\n backward,\n };\n return this;\n }\n\n this._metadata.foreignKeyType = config.toward.type.name;\n this._metadata.foreignKeyField = key;\n if (config.type === \"keyOnly\") {\n return this;\n }\n\n const forward = config.toward.as;\n this._ref = {\n type: config.toward.type,\n nameMap: [forward, backward],\n key,\n };\n this._metadata.relation = true;\n return this;\n }\n\n index<CurrentDefined extends Defined>(\n this: CurrentDefined extends { index: unknown }\n ? never\n : TailorDBField<CurrentDefined, Output>,\n ) {\n this._metadata.index = true;\n return this as TailorDBField<\n Prettify<CurrentDefined & { index: true }>,\n Output\n >;\n }\n\n unique<CurrentDefined extends Defined>(\n this: CurrentDefined extends { unique: unknown }\n ? never\n : TailorDBField<CurrentDefined, Output>,\n ) {\n this._metadata.unique = true;\n this._metadata.index = true;\n return this as TailorDBField<\n Prettify<CurrentDefined & { unique: true; index: true }>,\n Output\n >;\n }\n\n vector<CurrentDefined extends Defined>(\n this: CurrentDefined extends { vector: unknown }\n ? never\n : CurrentDefined extends { type: \"string\"; array: false }\n ? TailorDBField<CurrentDefined, Output>\n : never,\n ) {\n this._metadata.vector = true;\n return this as TailorDBField<\n Prettify<CurrentDefined & { vector: true }>,\n Output\n >;\n }\n\n hooks<CurrentDefined extends Defined, const H extends Hook<unknown, Output>>(\n this: CurrentDefined extends { hooks: unknown }\n ? never\n : CurrentDefined extends { type: \"nested\" }\n ? never\n : TailorDBField<CurrentDefined, Output>,\n hooks: H,\n ) {\n this._metadata.hooks = hooks;\n return this as TailorDBField<\n Prettify<\n CurrentDefined & {\n hooks?: {\n create: H extends { create: unknown } ? true : false;\n update: H extends { update: unknown } ? true : false;\n };\n serial: false;\n }\n >,\n Output\n >;\n }\n\n validate<CurrentDefined extends Defined>(\n this: CurrentDefined extends { validate: unknown }\n ? never\n : TailorDBField<CurrentDefined, Output>,\n ...validate: FieldValidateInput<Output>[]\n ) {\n this._metadata.validate = validate;\n return this as TailorDBField<\n Prettify<CurrentDefined & { validate: true }>,\n Output\n >;\n }\n\n serial<CurrentDefined extends Defined>(\n this: CurrentDefined extends { serial: unknown }\n ? never\n : Output extends null\n ? never\n : CurrentDefined extends { type: \"integer\" | \"string\"; array: false }\n ? TailorDBField<CurrentDefined, Output>\n : never,\n config: SerialConfig<CurrentDefined[\"type\"] & (\"integer\" | \"string\")>,\n ) {\n (this as TailorDBField<CurrentDefined, Output>)._metadata.serial = config;\n return this as TailorDBField<\n Prettify<\n CurrentDefined & {\n serial: true;\n hooks: { create: false; update: false };\n }\n >,\n Output\n >;\n }\n\n /**\n * Clone the field with optional overrides for field options\n * @param options - Optional field options to override\n * @returns A new TailorDBField instance with the same configuration\n */\n clone<const NewOpt extends FieldOptions>(\n options?: NewOpt,\n ): TailorDBField<\n Prettify<\n Omit<Defined, \"array\"> & {\n array: NewOpt extends { array: true } ? true : Defined[\"array\"];\n }\n >,\n FieldOutput<TailorToTs[Defined[\"type\"]], NewOpt>\n > {\n // Create a clone using Object.create to preserve prototype chain\n const clonedField = Object.create(\n Object.getPrototypeOf(this),\n ) as TailorDBField<Defined, Output>;\n\n // Copy all properties\n Object.assign(clonedField, {\n type: this.type,\n fields: this.fields,\n _defined: this._defined,\n _output: this._output,\n });\n\n // Clone and merge metadata with new options\n clonedField._metadata = { ...this._metadata };\n if (options) {\n if (options.optional !== undefined) {\n clonedField._metadata.required = !options.optional;\n }\n if (options.array !== undefined) {\n clonedField._metadata.array = options.array;\n }\n }\n\n // Copy internal state\n if (this._ref) {\n clonedField._ref = clone(this._ref);\n }\n if (this._pendingSelfRelation) {\n clonedField._pendingSelfRelation = { ...this._pendingSelfRelation };\n }\n\n return clonedField as TailorDBField<any, any>;\n }\n}\n\nconst createField = TailorDBField.create;\nfunction uuid<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"uuid\", options);\n}\n\nfunction string<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"string\", options);\n}\n\nfunction bool<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"boolean\", options);\n}\n\nfunction int<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"integer\", options);\n}\n\nfunction float<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"float\", options);\n}\n\nfunction date<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"date\", options);\n}\n\nfunction datetime<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"datetime\", options);\n}\n\nfunction time<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"time\", options);\n}\n\nfunction _enum<const V extends AllowedValues, const Opt extends FieldOptions>(\n values: V,\n options?: Opt,\n): TailorDBField<\n { type: \"enum\"; array: Opt extends { array: true } ? true : false },\n FieldOutput<AllowedValuesOutput<V>, Opt>\n> {\n return createField<\"enum\", Opt, AllowedValuesOutput<V>>(\n \"enum\",\n options,\n undefined,\n values,\n );\n}\n\nfunction object<\n const F extends Record<string, TailorDBField<any, any>> &\n ExcludeNestedDBFields<F>,\n const Opt extends FieldOptions,\n>(fields: F, options?: Opt) {\n return createField(\"nested\", options, fields) as unknown as TailorDBField<\n { type: \"nested\"; array: Opt extends { array: true } ? true : false },\n FieldOutput<InferFieldsOutput<F>, Opt>\n >;\n}\n\nexport class TailorDBType<\n const Fields extends Record<string, TailorDBField<any, any>> = any,\n User extends object = InferredAttributeMap,\n> {\n public readonly _output = null as unknown as InferFieldsOutput<Fields>;\n public _description?: string;\n private _settings: TypeFeatures = {};\n private _indexes: IndexDef<this>[] = [];\n private _permissions: Permissions = {};\n private _files: Record<string, string> = {};\n\n constructor(\n public readonly name: string,\n public readonly fields: Fields,\n options: { pluralForm?: string; description?: string },\n ) {\n this._description = options.description;\n\n if (options.pluralForm) {\n if (name === options.pluralForm) {\n throw new Error(\n `The name and the plural form must be different. name=${name}`,\n );\n }\n this._settings.pluralForm = options.pluralForm;\n }\n\n // Resolve any pending self-references now that the type is constructed\n Object.entries(this.fields).forEach(([fieldName, field]) => {\n const f = field as unknown as {\n _pendingSelfRelation: PendingSelfRelation | undefined;\n _metadata: DBFieldMetadata;\n _ref: ReferenceConfig<TailorDBType<any, any>>;\n };\n const pending = f._pendingSelfRelation;\n if (pending) {\n f._metadata.foreignKeyType = this.name;\n f._metadata.foreignKeyField = pending.key;\n if (pending.type === \"keyOnly\") {\n return this;\n }\n\n const forward = pending.as ?? fieldName.replace(/(ID|Id|id)$/u, \"\");\n // Type conversion for manipulating private _ref.\n f._ref = {\n type: this,\n nameMap: [forward, pending.backward],\n key: pending.key,\n };\n }\n });\n }\n\n get metadata(): TailorDBTypeConfig {\n const metadataFields = Object.entries(this.fields).reduce(\n (acc, [key, field]) => {\n acc[key] = field.config;\n return acc;\n },\n {} as Record<string, OperatorFieldConfig>,\n );\n\n // Convert indexes to the format expected by the manifest\n const indexes: Record<string, { fields: string[]; unique?: boolean }> = {};\n if (this._indexes && this._indexes.length > 0) {\n this._indexes.forEach((index) => {\n const fieldNames = index.fields.map((field) => String(field));\n const key = index.name || `idx_${fieldNames.join(\"_\")}`;\n indexes[key] = {\n fields: fieldNames,\n unique: index.unique,\n };\n });\n }\n\n return {\n name: this.name,\n schema: {\n description: this._description,\n extends: false,\n fields: metadataFields,\n settings: this._settings,\n permissions: this._permissions,\n files: this._files,\n ...(Object.keys(indexes).length > 0 && { indexes }),\n },\n };\n }\n\n hooks(hooks: Hooks<Fields>) {\n Object.entries(hooks).forEach(([fieldName, fieldHooks]: [string, any]) => {\n (this.fields[fieldName] as any).hooks(fieldHooks);\n });\n return this;\n }\n\n validate(validators: Validators<Fields>) {\n Object.entries(validators).forEach(([fieldName, fieldValidators]) => {\n const field = this.fields[fieldName] as TailorDBField<any, any>;\n\n const validators = fieldValidators as\n | FieldValidateInput<unknown>\n | FieldValidateInput<unknown>[];\n\n const isValidateConfig = (v: unknown): v is ValidateConfig<unknown> => {\n return Array.isArray(v) && v.length === 2 && typeof v[1] === \"string\";\n };\n\n if (Array.isArray(validators)) {\n if (isValidateConfig(validators)) {\n field.validate(validators);\n } else {\n field.validate(...validators);\n }\n } else {\n field.validate(validators);\n }\n });\n return this;\n }\n\n features(features: Omit<TypeFeatures, \"pluralForm\">) {\n this._settings = { ...this._settings, ...features };\n return this;\n }\n\n indexes(...indexes: IndexDef<this>[]) {\n this._indexes = indexes;\n return this;\n }\n\n files<const F extends string>(\n files: Record<F, string> & Partial<Record<keyof output<this>, never>>,\n ) {\n this._files = files;\n return this;\n }\n\n permission<\n U extends object = User,\n P extends TailorTypePermission<U, output<this>> = TailorTypePermission<\n U,\n output<this>\n >,\n >(permission: P) {\n const ret = this as TailorDBType<Fields, U>;\n ret._permissions.record = normalizePermission(permission);\n return ret;\n }\n\n gqlPermission<\n U extends object = User,\n P extends TailorTypeGqlPermission<U> = TailorTypeGqlPermission<U>,\n >(permission: P) {\n const ret = this as TailorDBType<Fields, U>;\n ret._permissions.gql = normalizeGqlPermission(permission);\n return ret;\n }\n\n description(description: string) {\n this._description = description;\n return this;\n }\n\n /**\n * Pick specific fields from the type\n * @param keys - Array of field keys to pick\n * @param options - Optional field options to apply to picked fields\n * @returns An object containing only the specified fields\n */\n pickFields<K extends keyof Fields, const Opt extends FieldOptions>(\n keys: K[],\n options: Opt,\n ) {\n const result = {} as Record<K, TailorDBField<any, any>>;\n for (const key of keys) {\n if (options) {\n result[key] = this.fields[key].clone(options);\n } else {\n result[key] = this.fields[key];\n }\n }\n return result as {\n [P in K]: Fields[P] extends TailorDBField<infer D, infer _O>\n ? TailorDBField<\n Omit<D, \"array\"> & {\n array: Opt extends { array: true } ? true : D[\"array\"];\n },\n FieldOutput<TailorToTs[D[\"type\"]], Opt>\n >\n : never;\n };\n }\n\n /**\n * Omit specific fields from the type\n * @param keys - Array of field keys to omit\n * @returns An object containing all fields except the specified ones\n */\n omitFields<K extends keyof Fields>(keys: K[]): Omit<Fields, K> {\n const keysSet = new Set(keys);\n const result = {} as Record<string, TailorDBField<any, any>>;\n for (const key in this.fields) {\n if (\n Object.hasOwn(this.fields, key) &&\n !keysSet.has(key as unknown as K)\n ) {\n result[key] = this.fields[key];\n }\n }\n return result as Omit<Fields, K>;\n }\n}\n\nexport type TailorDBInstance<\n Fields extends Record<string, TailorDBField<any, any>> = any,\n User extends object = InferredAttributeMap,\n> = InstanceType<typeof TailorDBType<Fields, User>>;\n\nconst idField = uuid();\ntype idField = typeof idField;\ntype DBType<\n F extends { id?: never } & Record<string, TailorDBField<any, any>>,\n> = TailorDBInstance<{ id: idField } & F>;\n\n/**\n * Creates a new database type with the specified fields\n * @param name - The name of the type, or a tuple of [name, pluralForm]\n * @param fields - The field definitions for the type\n * @returns A new TailorDBType instance\n */\nfunction dbType<\n const F extends { id?: never } & Record<string, TailorDBField<any, any>>,\n>(name: string | [string, string], fields: F): DBType<F>;\n/**\n * Creates a new database type with the specified fields and description\n * @param name - The name of the type, or a tuple of [name, pluralForm]\n * @param description - A description of the type\n * @param fields - The field definitions for the type\n * @returns A new TailorDBType instance\n */\nfunction dbType<\n const F extends { id?: never } & Record<string, TailorDBField<any, any>>,\n>(name: string | [string, string], description: string, fields: F): DBType<F>;\nfunction dbType<\n const F extends { id?: never } & Record<string, TailorDBField<any, any>>,\n>(\n name: string | [string, string],\n fieldsOrDescription: string | F,\n fields?: F,\n): DBType<F> {\n const typeName = Array.isArray(name) ? name[0] : name;\n const pluralForm = Array.isArray(name) ? name[1] : undefined;\n\n let description: string | undefined;\n let fieldDef: F;\n if (typeof fieldsOrDescription === \"string\") {\n description = fieldsOrDescription;\n fieldDef = fields as F;\n } else {\n fieldDef = fieldsOrDescription;\n }\n return new TailorDBType<{ id: idField } & F>(\n typeName,\n {\n id: idField,\n ...fieldDef,\n },\n { pluralForm, description },\n ) as DBType<F>;\n}\n\nexport const db = {\n type: dbType,\n uuid,\n string,\n bool,\n int,\n float,\n date,\n datetime,\n time,\n enum: _enum,\n object,\n fields: {\n timestamps: () => ({\n createdAt: datetime()\n .hooks({ create: () => new Date() })\n .description(\"Record creation timestamp\"),\n updatedAt: datetime({ optional: true })\n .hooks({ update: () => new Date() })\n .description(\"Record last update timestamp\"),\n }),\n },\n};\n","import type { AuthConfig } from \"@/configure/services/auth\";\nimport type { ExecutorServiceInput } from \"@/configure/services/executor/types\";\nimport type { IdPConfig } from \"@/configure/services/idp\";\nimport type { ResolverServiceInput } from \"@/configure/services/resolver/types\";\nimport type { StaticWebsiteConfig } from \"@/configure/services/staticwebsite\";\nimport type { TailorDBServiceInput } from \"@/configure/services/tailordb/types\";\nimport type { WorkflowServiceInput } from \"@/configure/services/workflow/types\";\nimport type { GeneratorConfig } from \"@/parser/generator-config/types\";\n\nexport interface AppConfig<\n Auth extends AuthConfig = AuthConfig,\n Idp extends IdPConfig[] = IdPConfig[],\n StaticWebsites extends StaticWebsiteConfig[] = StaticWebsiteConfig[],\n Env extends Record<string, string | number | boolean> = Record<\n string,\n string | number | boolean\n >,\n> {\n name: string;\n env?: Env;\n cors?: string[];\n allowedIPAddresses?: string[];\n disableIntrospection?: boolean;\n db?: TailorDBServiceInput;\n resolver?: ResolverServiceInput;\n idp?: Idp;\n auth?: Auth;\n executor?: ExecutorServiceInput;\n workflow?: WorkflowServiceInput;\n staticWebsites?: StaticWebsites;\n}\n\nlet distPath: string | null = null;\nexport const getDistDir = (): string => {\n const configured = process.env.TAILOR_SDK_OUTPUT_DIR;\n if (configured && configured !== distPath) {\n distPath = configured;\n } else if (distPath === null) {\n distPath = configured || \".tailor-sdk\";\n }\n return distPath;\n};\n\nexport function defineConfig<\n const Config extends AppConfig &\n // type-fest's Exact works recursively and causes type errors, so we use a shallow version here.\n Record<Exclude<keyof Config, keyof AppConfig>, never>,\n>(config: Config) {\n return config;\n}\n\nexport function defineGenerators(...configs: GeneratorConfig[]) {\n return configs;\n}\n","import { type TailorDBInstance } from \"../tailordb/schema\";\nimport type {\n AuthInvoker as ParserAuthInvoker,\n AuthServiceInput,\n UserAttributeListKey,\n UserAttributeMap,\n} from \"@/parser/service/auth/types\";\n\ndeclare const authDefinitionBrand: unique symbol;\ntype AuthDefinitionBrand = { readonly [authDefinitionBrand]: true };\n\nexport type {\n OIDC,\n SAML,\n IDToken,\n BuiltinIdP,\n IdProviderConfig,\n OAuth2ClientGrantType,\n OAuth2Client,\n SCIMAuthorization,\n SCIMAttributeType,\n SCIMAttribute,\n SCIMAttributeMapping,\n SCIMResource,\n SCIMConfig,\n TenantProviderConfig,\n ValueOperand,\n UsernameFieldKey,\n UserAttributeKey,\n UserAttributeListKey,\n UserAttributeMap,\n AuthServiceInput,\n} from \"@/parser/service/auth/types\";\n\n/**\n * Invoker type compatible with tailor.v1.AuthInvoker\n * - namespace: auth service name\n * - machineUserName: machine user name\n */\nexport type AuthInvoker<M extends string> = Omit<\n ParserAuthInvoker,\n \"machineUserName\"\n> & {\n machineUserName: M;\n};\n\nexport function defineAuth<\n const Name extends string,\n const User extends TailorDBInstance,\n const AttributeMap extends UserAttributeMap<User>,\n const AttributeList extends UserAttributeListKey<User>[],\n const MachineUserNames extends string,\n>(\n name: Name,\n config: AuthServiceInput<User, AttributeMap, AttributeList, MachineUserNames>,\n) {\n const result = {\n ...config,\n name,\n invoker<M extends MachineUserNames>(machineUser: M) {\n return { namespace: name, machineUserName: machineUser } as const;\n },\n } as const satisfies AuthServiceInput<\n User,\n AttributeMap,\n AttributeList,\n MachineUserNames\n > & {\n name: string;\n invoker<M extends MachineUserNames>(machineUser: M): AuthInvoker<M>;\n };\n\n return result as typeof result & AuthDefinitionBrand;\n}\n\nexport type AuthExternalConfig = { name: string; external: true };\n\nexport type AuthOwnConfig = ReturnType<\n typeof defineAuth<string, any, any, any, string>\n>;\n\nexport type AuthConfig = AuthOwnConfig | AuthExternalConfig;\n","import type { TailorEnv } from \"@/configure/types/env\";\nimport type { JsonCompatible } from \"@/configure/types/helpers\";\nimport type { Jsonifiable, Jsonify, JsonPrimitive } from \"type-fest\";\n\n/**\n * Symbol used to brand WorkflowJob objects created by createWorkflowJob.\n * This enables reliable runtime detection of workflow jobs regardless of\n * how they were imported or assigned (variable reassignment, destructuring, etc.)\n */\nexport const WORKFLOW_JOB_BRAND = Symbol.for(\"tailor:workflow-job\");\n\n/**\n * Context object passed as the second argument to workflow job body functions.\n */\nexport type WorkflowJobContext = {\n env: TailorEnv;\n};\n\n/**\n * Allowed output types for workflow job body functions.\n * Includes Jsonifiable (JSON-serializable values including objects with toJSON like Date),\n * undefined, and void.\n */\nexport type WorkflowJobOutput = Jsonifiable | undefined | void;\n\n/**\n * Convert output type to what trigger returns after JSON serialization.\n * - Jsonifiable values are converted via Jsonify (Date -> string, etc.)\n * - undefined remains undefined\n * - void becomes void\n */\ntype JsonifyOutput<T> = T extends Jsonifiable ? Jsonify<T> : T;\n\n/**\n * Input type constraint for workflow jobs.\n * Accepts any type that is JSON-compatible (primitives, arrays, objects with JSON-compatible values).\n * Excludes objects with toJSON method (like Date) since they won't be serialized in input.\n */\nexport type WorkflowJobInput = undefined | JsonCompatible<unknown>;\n\n/**\n * WorkflowJob represents a job that can be triggered in a workflow.\n *\n * Type constraints:\n * - Input: Must be JSON-compatible (no Date/toJSON objects) or undefined. Interfaces are allowed.\n * - Output: Must be Jsonifiable, undefined, or void\n * - Trigger returns Jsonify<Output> (Date becomes string after JSON.stringify)\n */\nexport interface WorkflowJob<\n Name extends string = string,\n Input = undefined,\n Output = undefined,\n> {\n readonly [WORKFLOW_JOB_BRAND]?: true;\n name: Name;\n /**\n * Trigger this job with the given input.\n * At runtime, this is a placeholder that calls the body function.\n * During bundling, calls to .trigger() are transformed to\n * tailor.workflow.triggerJobFunction(\"<job-name>\", args).\n *\n * Returns Jsonify<Output> because the value passes through JSON.stringify.\n */\n trigger: [Input] extends [undefined]\n ? () => Promise<JsonifyOutput<Awaited<Output>>>\n : (input: Input) => Promise<JsonifyOutput<Awaited<Output>>>;\n body: (input: Input, context: WorkflowJobContext) => Output | Promise<Output>;\n}\n\n/**\n * Check if a type contains any non-JSON-compatible values.\n * Returns `true` if the type is valid for input, `false` otherwise.\n */\ntype IsValidInput<T> = T extends undefined\n ? true\n : T extends JsonPrimitive\n ? true\n : T extends readonly (infer U)[]\n ? IsValidInput<U>\n : T extends object\n ? T extends { toJSON: () => unknown }\n ? false\n : { [K in keyof T]: IsValidInput<T[K]> }[keyof T] extends true\n ? true\n : false\n : false;\n\n/**\n * Check if a type is valid for output.\n * Returns `true` if the type is valid, `false` otherwise.\n */\ntype IsValidOutput<T> = T extends undefined | void\n ? true\n : T extends JsonPrimitive\n ? true\n : T extends readonly (infer U)[]\n ? IsValidOutput<U>\n : T extends object\n ? { [K in keyof T]: IsValidOutput<T[K]> }[keyof T] extends true\n ? true\n : false\n : false;\n\n/**\n * Body function type with conditional constraint.\n * If input contains invalid types (like Date), the body type becomes `never` to cause an error.\n */\ntype WorkflowJobBody<I, O> =\n IsValidInput<I> extends true\n ? IsValidOutput<O> extends true\n ? (input: I, context: WorkflowJobContext) => O | Promise<O>\n : never\n : never;\n\nexport const createWorkflowJob = <\n const Name extends string,\n I = undefined,\n O = undefined,\n>(config: {\n readonly name: Name;\n readonly body: WorkflowJobBody<I, O>;\n}): WorkflowJob<Name, I, Awaited<O>> => {\n return {\n [WORKFLOW_JOB_BRAND]: true,\n name: config.name,\n // JSON.parse(JSON.stringify(...)) ensures the return value matches Jsonify<Output> type.\n // This converts Date objects to strings, matching actual runtime behavior.\n trigger: async (args?: unknown) => {\n const ret = await tailor.workflow.triggerJobFunction(config.name, args);\n return ret ? JSON.parse(JSON.stringify(ret)) : ret;\n },\n body: config.body,\n } as WorkflowJob<Name, I, Awaited<O>>;\n};\n"],"mappings":";;;AAMA,SAAgB,iBAAiB,QAAuC;AACtE,QAAO,OAAO,KAAK,UAAU;AAC3B,MAAI,OAAO,UAAU,SACnB,QAAO;GAAE;GAAO,aAAa;GAAI;AAEnC,SAAO;GAAE,GAAG;GAAO,aAAa,MAAM,eAAe;GAAI;GACzD;;;;;ACOJ,MAAM,QAAQ;CACZ,MAAM;CACN,MAAM;CACN,MAAM;CACN,UACE;CACH;AAED,IAAa,cAAb,MAAa,YAIiB;CAC5B,AAAU;CACV,AAAgB,WAAoB;CACpC,AAAgB,UAAU;CAE1B,IAAI,WAAW;AACb,SAAO,EAAE,GAAG,KAAK,WAAW;;CAG9B,AAAU,YACR,AAAgBA,MAChB,S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WAAW;IAAM,iBAAiB;IAAa;;EAE3D;;;;;;;;;;ACrDH,MAAa,qBAAqB,OAAO,IAAI,sBAAsB;AAyGnE,MAAa,qBAIX,WAGsC;AACtC,QAAO;GACJ,qBAAqB;EACtB,MAAM,OAAO;EAGb,SAAS,OAAO,SAAmB;GACjC,MAAM,MAAM,MAAM,OAAO,SAAS,mBAAmB,OAAO,MAAM,KAAK;AACvE,UAAO,MAAM,KAAK,MAAM,KAAK,UAAU,IAAI,CAAC,GAAG;;EAEjD,MAAM,OAAO;EACd"}
@@ -1,4 +1,4 @@
1
- import { WORKFLOW_JOB_BRAND, getDistDir, tailorUserMap } from "./job-Dx7eROGy.mjs";
1
+ import { WORKFLOW_JOB_BRAND, getDistDir, tailorUserMap } from "./job-CL8myeqs.mjs";
2
2
  import Module, { createRequire } from "node:module";
3
3
  import { defineCommand } from "citty";
4
4
  import * as path$1 from "node:path";
@@ -374,7 +374,7 @@ const GqlOperationSchema = z.object({
374
374
  const WebhookOperationSchema = z.object({
375
375
  kind: z.literal("webhook"),
376
376
  url: functionSchema,
377
- body: functionSchema.optional(),
377
+ requestBody: functionSchema.optional(),
378
378
  headers: z.record(z.string(), z.union([z.string(), z.object({
379
379
  vault: z.string(),
380
380
  key: z.string()
@@ -146285,6 +146285,20 @@ async function confirmImportantResourceDeletion(resources, yes) {
146285
146285
 
146286
146286
  //#endregion
146287
146287
  //#region src/cli/apply/services/executor.ts
146288
+ /**
146289
+ * Convert a function to a string representation.
146290
+ * Handles method shorthand syntax (e.g., `requestBody() { ... }`) by converting it to
146291
+ * a function expression (e.g., `function requestBody() { ... }`).
146292
+ *
146293
+ * TODO: This function should be moved to the parser module.
146294
+ * The same function exists in `src/configure/services/tailordb/schema.ts`.
146295
+ * These should be unified into a common utility in the parser layer.
146296
+ */
146297
+ const stringifyFunction = (fn) => {
146298
+ const src = fn.toString().trim();
146299
+ if (/^[a-zA-Z_$][a-zA-Z0-9_$]*\s*\(/.test(src) && !src.startsWith("function") && !src.startsWith("(") && !src.includes("=>")) return `function ${src}`;
146300
+ return src;
146301
+ };
146288
146302
  async function applyExecutor(client, result, phase = "create-update") {
146289
146303
  const { changeSet } = result;
146290
146304
  if (phase === "create-update") await Promise.all([...changeSet.creates.map(async (create$1) => {
@@ -146404,7 +146418,7 @@ function protoExecutor(appName, executor, env$1) {
146404
146418
  case: "event",
146405
146419
  value: {
146406
146420
  eventType: eventType[trigger.kind],
146407
- condition: { expr: [`args.typeName === "${trigger.typeName}"`, ...trigger.condition ? [`(${trigger.condition.toString()})({ ...args, appNamespace: args.namespaceName })`] : []].join(" && ") }
146421
+ condition: { expr: [`args.typeName === "${trigger.typeName}"`, ...trigger.condition ? [`(${stringifyFunction(trigger.condition)})({ ...args, appNamespace: args.namespaceName })`] : []].join(" && ") }
146408
146422
  }
146409
146423
  } };
146410
146424
  break;
@@ -146414,7 +146428,7 @@ function protoExecutor(appName, executor, env$1) {
146414
146428
  case: "event",
146415
146429
  value: {
146416
146430
  eventType: eventType[trigger.kind],
146417
- condition: { expr: [`args.resolverName === "${trigger.resolverName}"`, ...trigger.condition ? [`(${trigger.condition.toString()})({ ...args, appNamespace: args.namespaceName, result: args.succeeded?.result, error: args.failed?.error })`] : []].join(" && ") }
146431
+ condition: { expr: [`args.resolverName === "${trigger.resolverName}"`, ...trigger.condition ? [`(${stringifyFunction(trigger.condition)})({ ...args, appNamespace: args.namespaceName, result: args.succeeded?.result, error: args.failed?.error })`] : []].join(" && ") }
146418
146432
  }
146419
146433
  } };
146420
146434
  break;
@@ -146436,7 +146450,7 @@ function protoExecutor(appName, executor, env$1) {
146436
146450
  targetConfig = { config: {
146437
146451
  case: "webhook",
146438
146452
  value: {
146439
- url: { expr: `(${target.url.toString()})(args)` },
146453
+ url: { expr: `(${stringifyFunction(target.url)})(args)` },
146440
146454
  headers: target.headers ? Object.entries(target.headers).map(([key, v]) => {
146441
146455
  let value$1;
146442
146456
  if (typeof v === "string") value$1 = {
@@ -146455,7 +146469,7 @@ function protoExecutor(appName, executor, env$1) {
146455
146469
  value: value$1
146456
146470
  };
146457
146471
  }) : void 0,
146458
- body: target.body ? { expr: `(${target.body.toString()})(args)` } : void 0
146472
+ body: target.requestBody ? { expr: `(${stringifyFunction(target.requestBody)})(args)` } : void 0
146459
146473
  }
146460
146474
  } };
146461
146475
  break;
@@ -146466,7 +146480,7 @@ function protoExecutor(appName, executor, env$1) {
146466
146480
  value: {
146467
146481
  appName: target.appName ?? appName,
146468
146482
  query: target.query,
146469
- variables: target.variables ? { expr: `(${target.variables.toString()})(args)` } : void 0,
146483
+ variables: target.variables ? { expr: `(${stringifyFunction(target.variables)})(args)` } : void 0,
146470
146484
  invoker: target.authInvoker ?? void 0
146471
146485
  }
146472
146486
  } };
@@ -147473,7 +147487,7 @@ function filterJobFunctionVersions(allVersions, usedJobNames) {
147473
147487
  /**
147474
147488
  * Register job functions used by any workflow.
147475
147489
  * Only registers jobs that are actually used (based on usedJobNames in changeSet).
147476
- * Uses update for existing workflows, create for new workflows.
147490
+ * Uses create for new jobs and update for existing jobs.
147477
147491
  */
147478
147492
  async function registerJobFunctions(client, changeSet) {
147479
147493
  const jobFunctionVersions = {};
@@ -147482,11 +147496,18 @@ async function registerJobFunctions(client, changeSet) {
147482
147496
  const { workspaceId, scripts } = firstWorkflow;
147483
147497
  const allUsedJobNames = /* @__PURE__ */ new Set();
147484
147498
  for (const item of [...changeSet.creates, ...changeSet.updates]) for (const jobName of item.usedJobNames) allUsedJobNames.add(jobName);
147485
- const hasExistingWorkflows = changeSet.updates.length > 0;
147499
+ const existingJobNames = await fetchAll(async (pageToken) => {
147500
+ const response = await client.listWorkflowJobFunctions({
147501
+ workspaceId,
147502
+ pageToken
147503
+ });
147504
+ return [response.jobFunctions.map((j) => j.name), response.nextPageToken];
147505
+ });
147506
+ const existingJobNamesSet = new Set(existingJobNames);
147486
147507
  const results = await Promise.all(Array.from(allUsedJobNames).map(async (jobName) => {
147487
147508
  const script = scripts.get(jobName);
147488
147509
  if (!script) throw new Error(`No bundled script found for job "${jobName}". Please run "generate" command before "apply".`);
147489
- const response = hasExistingWorkflows ? await client.updateWorkflowJobFunction({
147510
+ const response = existingJobNamesSet.has(jobName) ? await client.updateWorkflowJobFunction({
147490
147511
  workspaceId,
147491
147512
  jobFunctionName: jobName,
147492
147513
  script
@@ -149932,4 +149953,4 @@ const resumeCommand = defineCommand({
149932
149953
 
149933
149954
  //#endregion
149934
149955
  export { PATScope, apply, applyCommand, commonArgs, createCommand, deleteCommand, executionsCommand, fetchAll, fetchLatestToken, fetchUserInfo, formatArgs, generate, generateCommand, generateUserTypes, getCommand, getCommand$1, initOAuth2Client, initOperatorClient, listCommand, listCommand$1, listCommand$2, listCommand$3, loadAccessToken, loadConfig, loadWorkspaceId, machineUserList, machineUserToken, oauth2ClientGet, oauth2ClientList, parseFormat, printWithFormat, readPackageJson, readPlatformConfig, remove, removeCommand, resumeCommand, show, showCommand, startCommand, tokenCommand, withCommonArgs, workflowExecutionGet, workflowExecutionsList, workflowGet, workflowList, workflowResume, workflowStart, workspaceCreate, workspaceDelete, workspaceList, writePlatformConfig };
149935
- //# sourceMappingURL=resume-DJfAvxVb.mjs.map
149956
+ //# sourceMappingURL=resume-DvbIclRU.mjs.map