Skip to content

Commit 8e1ff50

Browse files
committed
Sync alphalib
1 parent 94356cb commit 8e1ff50

File tree

11 files changed

+2135
-577
lines changed

11 files changed

+2135
-577
lines changed

package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
"node": ">= 18"
1717
},
1818
"dependencies": {
19+
"@aws-sdk/client-s3": "^3.726.1",
20+
"@aws-sdk/s3-request-presigner": "^3.726.1",
1921
"debug": "^4.3.7",
2022
"form-data": "^4.0.1",
2123
"got": "^11.8.6",

src/alphalib/types/robots/_instructions-primitives.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,6 @@ export const imageQualitySchema = z.number().int().min(1).max(100).default(92).d
436436
Controls the image compression for JPG and PNG images. Please also take a look at [🤖/image/optimize](/docs/transcoding/image-manipulation/image-optimize/).
437437
`)
438438

439-
export const aiProviderSchema = z.enum(['aws', 'gcp'])
439+
export const aiProviderSchema = z.enum(['aws', 'gcp', 'replicate', 'fal', 'transloadit'])
440440

441441
export const granularitySchema = z.enum(['full', 'list']).default('full')

src/alphalib/types/robots/file-filter.ts

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,46 @@ export const robotFileFilterInstructionsSchema = z
4040
.boolean()
4141
.optional()
4242
.describe(`Whether the results of this Step should be present in the Assembly Status JSON`),
43-
robot: z.literal('/file/filter'),
43+
robot: z.literal('/file/filter').describe(`
44+
Think of this <dfn>Robot</dfn> as an \`if/else\` condition for building advanced file conversion workflows. With it, you can filter and direct certain uploaded files depending on their metadata.
45+
46+
The <dfn>Robot</dfn> has two modes of operation:
47+
48+
- Constructing conditions out of arrays with 3 members each. For example, \`["\${file.size}", "<=", "720"]\`
49+
- Writing conditions in JavaScript. For example, \`\${file.size <= 720}\`. See also [Dynamic Evaluation](/docs/topics/dynamic-evaluation/).
50+
51+
Passing JavaScript allows you to implement logic as complex as you wish, however it’s slower than combining arrays of conditions, and will be charged for per invocation via [🤖/script/run]({{robot_links["/script/run"]}}).
52+
53+
### Conditions as arrays
54+
55+
The \`accepts\` and \`declines\` parameters can each be set to an array of arrays with three members:
56+
57+
1. A value or job variable, such as \`\${file.mime}\`
58+
2. One of the following operators: \`==\`, \`===\`, \`<\`, \`>\`, \`<=\`, \`>=\`, \`!=\`, \`!==\`, \`regex\`, \`!regex\`
59+
3. A value or job variable, such as \`50\` or \`"foo"\`
60+
61+
Examples:
62+
63+
- \`[["\${file.meta.width}", ">", "\${file.meta.height}"]]\`
64+
- \`[["\${file.size}", "<=", "720"]]\`
65+
- \`[["720", ">=", "\${file.size}"]]\`
66+
- \`[["\${file.mime}", "regex", "image"]]\`
67+
68+
**Warning:** If you would like to match against a \`null\` value or a value that is not present (like an audio file does not have a \`video_codec\` property in its metadata), match against \`""\` (an empty string) instead. We’ll support proper matching against \`null\` in the future, but we cannot easily do so right now without breaking backwards compatibility. [{.alert .alert-warning}]
69+
70+
### Conditions as JavaScript
71+
72+
The \`accepts\` and \`declines\` parameters can each be set to strings of JavaScript, which return a boolean value.
73+
74+
Examples:
75+
76+
- \`\${file.meta.width > file.meta.height}\`
77+
- \`\${file.size <= 720}\`
78+
- \`\${/image/.test(file.mime)}\`
79+
- \`\${Math.max(file.meta.width, file.meta.height) > 100}\`
80+
81+
As indicated, we charge for this via [🤖/script/run]({{robot_links["/script/run"]}}). See also [Dynamic Evaluation](/docs/topics/dynamic-evaluation/) for more details on allowed syntax and behavior.
82+
`),
4483
use: useParamSchema,
4584
accepts: z
4685
.array(

src/alphalib/types/robots/file-virusscan.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,13 @@ export const robotFileVirusscanInstructionsSchema = z
4444
.boolean()
4545
.optional()
4646
.describe(`Whether the results of this Step should be present in the Assembly Status JSON`),
47-
robot: z.literal('/file/virusscan'),
47+
robot: z.literal('/file/virusscan').describe(`
48+
This <dfn>Robot</dfn> is built on top of [ClamAV](https://www.clamav.net/), the best open source antivirus engine available. We update its signatures on a daily basis.
49+
50+
By default, this <dfn>Robot</dfn> excludes all malicious files from further processing without any additional notification. This behavior can be changed by setting \`error_on_decline\` to \`true\`, which will stop <dfn>Assemblies</dfn> as soon as malicious files are found. Such <dfn>Assemblies</dfn> will then be marked with an error.
51+
52+
We allow the use of industry standard [EICAR files](https://www.eicar.org/download-anti-malware-testfile/) for integration testing without needing to use potentially dangerous live virus samples.
53+
`),
4854
use: useParamSchema,
4955
error_on_decline: z.boolean().default(false).describe(`
5056
If this is set to \`true\` and one or more files are declined, the Assembly will be stopped and marked with an error.

src/alphalib/types/robots/http-import.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,18 @@ export const robotHttpImportInstructionsSchema = z
3838
.boolean()
3939
.optional()
4040
.describe(`Whether the results of this Step should be present in the Assembly Status JSON`),
41-
robot: z.literal('/http/import'),
41+
robot: z.literal('/http/import').describe(`
42+
The result of this <dfn>Robot</dfn> will carry a field \`import_url\` in their metadata, which references the URL from which they were imported. Further conversion results that use this file will also carry this \`import_url\` field. This allows you to to match conversion results with the original import URL that you used.
43+
44+
This <dfn>Robot</dfn> knows to interpret links to files on these services:
45+
46+
- Dropbox
47+
- Google Drive
48+
- Google Docs
49+
- OneDrive
50+
51+
Instead of downloading the HTML page previewing the file, the actual file itself will be imported.
52+
`),
4253
ignore_errors,
4354
url: z.union([z.string().url(), z.array(z.string().url())]).describe(`
4455
The URL from which the file to be imported can be retrieved.

src/alphalib/types/robots/image-remove-background.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,15 @@ export const robotImageRemoveBackgroundInstructionsSchema = z
99
.optional()
1010
.describe(`Whether the results of this Step should be present in the Assembly Status JSON`),
1111
robot: z.literal('/image/remove-background'),
12-
endpoint: z.string().describe('The URL of the destination Tus server'),
1312
select: z
1413
.enum(['foreground', 'background'])
1514
.optional()
1615
.describe('Region to select and keep in the image. The other region is removed.'),
1716
format: z.enum(['png', 'gif', 'webp']).optional().describe('Format of the generated image.'),
17+
provider: z
18+
.enum(['transloadit', 'replicate', 'fal'])
19+
.optional()
20+
.describe('Provider to use for removing the background.'),
1821
output_meta: outputMetaParamSchema.optional(),
1922
use: useParamSchema,
2023
})

src/alphalib/types/robots/image-resize.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -161,9 +161,9 @@ Controls the image compression for PNG images. Setting to \`true\` results in sm
161161
background: z
162162
.union([z.literal('transparent'), z.literal('none'), color_without_alpha])
163163
.default('#FFFFFF').describe(`
164-
Either the hexadecimal code or [name](https://www.imagemagick.org/script/color.php#color_names) of the color used to fill the background (only used for the pad resize strategy).
164+
Either the hexadecimal code or [name](https://www.imagemagick.org/script/color.php#color_names) of the color used to fill the background (used for the \`pad\` resize strategy).
165165
166-
By default, the background of transparent images is changed to white. For details about how to preserve transparency across all image types, see [this demo](/demos/image-manipulation/properly-preserve-transparency-across-all-image-types/).
166+
**Note:** By default, the background of transparent images is changed to white. To preserve transparency, set \`"background"\` to \`"none"\`.
167167
`),
168168
frame: z.number().int().min(1).nullable().default(null).describe(`
169169
Use this parameter when dealing with animated GIF files to specify which frame of the GIF is used for the operation. Specify \`1\` to use the first frame, \`2\` to use the second, and so on. \`null\` means all frames.

src/alphalib/types/robots/s3-import.ts

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,43 @@ export const robotS3ImportInstructionsSchema = z
4949
.boolean()
5050
.optional()
5151
.describe(`Whether the results of this Step should be present in the Assembly Status JSON`),
52-
robot: z.literal('/s3/import'),
52+
robot: z.literal('/s3/import').describe(`
53+
If you are new to Amazon S3, see our tutorial on [using your own S3 bucket](/docs/faq/how-to-set-up-an-amazon-s3-bucket/).
54+
55+
The URL to the result file in your S3 bucket will be returned in the <dfn>Assembly Status JSON</dfn>.
56+
57+
**Use DNS-compliant bucket names.** Your bucket name [must be DNS-compliant](https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html) and must not contain uppercase letters. Any non-alphanumeric characters in the file names will be replaced with an underscore, and spaces will be replaced with dashes. If your existing S3 bucket contains uppercase letters or is otherwise not DNS-compliant, rewrite the result URLs using the <dfn>Robot</dfn>’s \`url_prefix\` parameter. [{.alert .alert-warning}]
58+
59+
<a id="minimum-s3-iam-permissions" aria-hidden="true"></a>
60+
61+
## Limit access
62+
63+
You will also need to add permissions to your bucket so that Transloadit can access it properly. Here is an example IAM policy that you can use. Following the [principle of least privilege](https://en.wikipedia.org/wiki/Principle_of_least_privilege), it contains the **minimum required permissions** to export a file to your S3 bucket using Transloadit. You may require more permissions (especially viewing permissions) depending on your application.
64+
65+
Please change \`{BUCKET_NAME}\` in the values for \`Sid\` and \`Resource\` accordingly. Also, this policy will grant the minimum required permissions to all your users. We advise you to create a separate Amazon IAM user, and use its User ARN (can be found in the "Summary" tab of a user [here](https://console.aws.amazon.com/iam/home#users)) for the \`Principal\` value. More information about this can be found [here](https://docs.aws.amazon.com/AmazonS3/latest/dev/AccessPolicyLanguage_UseCases_s3_a.html).
66+
67+
\`\`\`json
68+
{
69+
"Version": "2012-10-17",
70+
"Statement": [
71+
{
72+
"Sid": "AllowTransloaditToImportFilesIn{BUCKET_NAME}Bucket",
73+
"Effect": "Allow",
74+
"Action": ["s3:GetBucketLocation", "s3:ListBucket"],
75+
"Resource": ["arn:aws:s3:::{BUCKET_NAME}", "arn:aws:s3:::{BUCKET_NAME}/*"]
76+
}
77+
]
78+
}
79+
\`\`\`
80+
81+
The \`Sid\` value is just an identifier for you to recognize the rule later. You can name it anything you like.
82+
83+
The policy needs to be separated into two parts, because the \`ListBucket\` action requires permissions on the bucket while the other actions require permissions on the objects in the bucket. When targeting the objects there's a trailing slash and an asterisk in the \`Resource\` parameter, whereas when the policy targets the bucket, the slash and the asterisk are omitted.
84+
85+
In order to build proper result URLs we need to know the region in which your S3 bucket resides. For this we require the \`GetBucketLocation\` permission. Figuring out your bucket's region this way will also slow down your Assemblies. To make this much faster and to also not require the \`GetBucketLocation\` permission, we have added the \`bucket_region\` parameter to the /s3/store and /s3/import Robots. We recommend using them at all times.
86+
87+
Please keep in mind that if you use bucket encryption you may also need to add \`"sts:*"\` and \`"kms:*"\` to the bucket policy. Please read [here](https://docs.aws.amazon.com/kms/latest/developerguide/kms-api-permissions-reference.html) and [here](https://aws.amazon.com/blogs/security/how-to-restrict-amazon-s3-bucket-access-to-a-specific-iam-role/) in case you run into trouble with our example bucket policy.
88+
`),
5389
ignore_errors,
5490
credentials: credentials.describe(`
5591
Please create your associated <dfn>Template Credentials</dfn> in your Transloadit account and use the name of your <dfn>Template Credentials</dfn> as this parameter's value. They will contain the values for your S3 bucket, Key, Secret and Bucket region.

src/alphalib/types/robots/supabase-store.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ export const meta: RobotMeta = {
2525
override_lvl1: 'File Exporting',
2626
purpose_sentence: 'exports encoding results to supabase buckets',
2727
purpose_verb: 'export',
28-
purpose_word: 'supabase',
28+
purpose_word: 'Supabase',
2929
purpose_words: 'Export files to Supabase',
3030
service_slug: 'file-exporting',
3131
slot_count: 10,
Lines changed: 110 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { z } from 'zod'
22

3-
type ZodIssueWithContext = z.ZodIssue & { parentObj: unknown }
3+
export type ZodIssueWithContext = z.ZodIssue & { parentObj: unknown }
44

55
function getByPath(obj: unknown, path: string): unknown {
66
if (!path) return obj
@@ -13,28 +13,129 @@ function getByPath(obj: unknown, path: string): unknown {
1313
return current
1414
}
1515

16+
interface ZodParseWithContextResult<T extends z.ZodType> {
17+
success: boolean
18+
safe?: z.infer<T>
19+
errors: ZodIssueWithContext[]
20+
humanReadable: string
21+
}
22+
1623
export function zodParseWithContext<T extends z.ZodType>(
1724
schema: T,
1825
obj: unknown,
19-
): { success: boolean; safe?: z.infer<T>; errors: ZodIssueWithContext[] } {
26+
): ZodParseWithContextResult<T> {
2027
const zodRes = schema.safeParse(obj)
2128
if (!zodRes.success) {
22-
const reportErrors: ZodIssueWithContext[] = []
23-
for (const error of zodRes.error.errors) {
24-
const lastPath = error.path
29+
const zodIssuesWithContext: ZodIssueWithContext[] = []
30+
for (const zodIssue of zodRes.error.errors) {
31+
const lastPath = zodIssue.path
2532
let parentObj: unknown = {}
2633
if (lastPath) {
2734
const strPath = lastPath.slice(0, -1).join('.')
2835
parentObj = getByPath(obj, strPath) ?? {}
2936
}
3037

31-
reportErrors.push({
32-
...error,
38+
zodIssuesWithContext.push({
39+
...zodIssue,
3340
parentObj,
3441
})
3542
}
36-
return { success: false, errors: reportErrors }
43+
44+
const badPaths = new Map<string, string[]>()
45+
for (const issue of zodIssuesWithContext) {
46+
const path = issue.path
47+
.map((p) => (typeof p === 'string' ? p.replaceAll('.', '\\.') : p))
48+
.join('.')
49+
if (!badPaths.has(path)) {
50+
badPaths.set(path, [])
51+
}
52+
53+
// Handle union type validation errors (e.g., when a value must be one of several allowed values)
54+
// For example: z.union([z.literal(0), z.literal(90), z.literal(180)]) for rotation values
55+
// This extracts all the valid values from the union type to show in the error message
56+
if ('unionErrors' in issue && issue.unionErrors) {
57+
const validValues: (string | number | boolean)[] = []
58+
for (const unionError of issue.unionErrors) {
59+
if (
60+
Array.isArray(unionError.errors) &&
61+
unionError.errors[0]?.code === 'invalid_literal'
62+
) {
63+
const { expected } = unionError.errors[0]
64+
if (
65+
expected !== undefined &&
66+
expected !== null &&
67+
(typeof expected === 'string' ||
68+
typeof expected === 'number' ||
69+
typeof expected === 'boolean')
70+
) {
71+
validValues.push(expected)
72+
}
73+
}
74+
}
75+
if (validValues.length > 0) {
76+
badPaths.get(path)?.push(`should be one of: \`${validValues.join('`, `')}\``)
77+
} else {
78+
for (const unionError of issue.unionErrors) {
79+
if ('expected' in unionError && typeof unionError.expected === 'string') {
80+
badPaths.get(path)?.push(`should be ${unionError.expected}`)
81+
} else {
82+
badPaths.get(path)?.push(unionError.message)
83+
}
84+
}
85+
}
86+
} else if ('expected' in issue && typeof issue.expected === 'string') {
87+
badPaths.get(path)?.push(`should be ${issue.expected}`)
88+
} else {
89+
// Handle specific error codes for better messages
90+
let received: string
91+
let type: string
92+
let bigType: string
93+
94+
// Handle different validation error types with specific human-readable messages
95+
// Each case formats the error message based on the type of validation that failed:
96+
// - invalid_type: Wrong data type (e.g., string instead of number)
97+
// - invalid_string: String format validation (email, url)
98+
// - too_small/too_big: Length/size validations for strings and arrays
99+
switch (issue.code) {
100+
case 'invalid_type':
101+
received = issue.received === 'undefined' ? 'missing' : issue.received
102+
badPaths.get(path)?.push(`should be ${issue.expected} but got ${received}`)
103+
break
104+
case 'invalid_string':
105+
if (issue.validation === 'email') {
106+
badPaths.get(path)?.push('should be a valid email address')
107+
} else if (issue.validation === 'url') {
108+
badPaths.get(path)?.push('should be a valid URL')
109+
} else {
110+
badPaths.get(path)?.push(issue.message)
111+
}
112+
break
113+
case 'too_small':
114+
type = issue.type === 'string' ? 'characters' : 'items'
115+
badPaths.get(path)?.push(`should have at least ${issue.minimum} ${type}`)
116+
break
117+
case 'too_big':
118+
bigType = issue.type === 'string' ? 'characters' : 'items'
119+
badPaths.get(path)?.push(`should have at most ${issue.maximum} ${bigType}`)
120+
break
121+
case 'custom':
122+
badPaths.get(path)?.push(issue.message)
123+
break
124+
default:
125+
badPaths.get(path)?.push(issue.message)
126+
}
127+
}
128+
}
129+
130+
const humanReadable = Array.from(badPaths.entries())
131+
.map(([path, messages]) => {
132+
const field = path || 'Input'
133+
return `Path \`${field}\` ${messages.join(', ')}`
134+
})
135+
.join('\n')
136+
137+
return { success: false, errors: zodIssuesWithContext, humanReadable }
37138
}
38139

39-
return { success: true, safe: zodRes.data, errors: [] }
140+
return { success: true, safe: zodRes.data, errors: [], humanReadable: '' }
40141
}

0 commit comments

Comments
 (0)