@sentry/junior-vimeo 0.0.0-stage → 0.316.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,18 @@
1
- # Temporary Holding Version
1
+ # @sentry/junior-vimeo
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Private Vimeo uploads for Junior: list the Vimeo folders the account can reach, upload sandbox videos into the folder that each call names, replace their files and thumbnails, and check their processing. One shared Vimeo account, connected by an admin.
4
+
5
+ ```bash
6
+ pnpm add @sentry/junior @sentry/junior-vimeo
7
+ ```
8
+
9
+ ```ts
10
+ import { defineJuniorPlugins } from "@sentry/junior";
11
+ import { vimeoPlugin } from "@sentry/junior-vimeo";
12
+
13
+ export const plugins = defineJuniorPlugins([
14
+ vimeoPlugin({ embedDomains: ["www.example.com"] }),
15
+ ]);
16
+ ```
17
+
18
+ Setup and configuration: https://junior.sentry.dev/extend/vimeo-plugin/
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Vimeo plugin runtime boundary.
3
+ *
4
+ * The tools list the Vimeo folders the account can reach, upload sandbox
5
+ * videos into the folder that each call names as private videos, replace
6
+ * their files and thumbnails, and read their state. They run on the
7
+ * host and send files with tus in chunks, so sandbox request limits do not
8
+ * apply. Junior uses only the plugin's service account: an admin connects
9
+ * one shared Vimeo account, and people never connect their own. Junior adds
10
+ * its token to the plugin's API calls on the host.
11
+ *
12
+ * Every upload is private when Vimeo creates it: hidden from vimeo.com or
13
+ * unlisted, embeddable only on allowed domains, and not downloadable. No
14
+ * tool can make a video public.
15
+ */
16
+ import { PluginRegistration } from "@sentry/junior-plugin-api";
17
+ import "zod";
18
+ /** Install settings that the app passes to `vimeoPlugin()`. */
19
+ interface VimeoPluginOptions {
20
+ /** Hostnames where an upload may be embedded when the call names none. */
21
+ embedDomains?: string[];
22
+ }
23
+ /** Register the Vimeo upload, file, thumbnail, status, and folder tools. */
24
+ export declare function vimeoPlugin(options?: VimeoPluginOptions): PluginRegistration;
25
+ export type { VimeoPluginOptions };
package/dist/index.js ADDED
@@ -0,0 +1,620 @@
1
+ import { PluginToolInputError, defineJuniorPlugin, definePluginTool, pluginToolOutputSchema } from "@sentry/junior-plugin-api";
2
+ import * as z from "zod";
3
+ import path from "node:path";
4
+ // src/tool-support/vimeo-api.ts
5
+ /**
6
+ * Vimeo API calls and the shared shapes of the Vimeo tools.
7
+ *
8
+ * Every API call goes through plugin egress with one operation per tool.
9
+ * Junior adds the service account's token on the host, so plugin code, the
10
+ * sandbox, and the model never hold it.
11
+ */
12
+ const API = "https://api.vimeo.com";
13
+ /** One egress operation per tool. The service account serves only these. */
14
+ const VIMEO_OPERATIONS = {
15
+ upload: "vimeo.upload",
16
+ replaceFile: "vimeo.replace_file",
17
+ setThumbnail: "vimeo.set_thumbnail",
18
+ status: "vimeo.status",
19
+ listFolder: "vimeo.list_folder",
20
+ listFolders: "vimeo.list_folders"
21
+ };
22
+ /** Fields that the tools read from a Vimeo video. */
23
+ const VIDEO_FIELDS = [
24
+ "uri",
25
+ "name",
26
+ "link",
27
+ "player_embed_url",
28
+ "privacy",
29
+ "status",
30
+ "upload.status",
31
+ "transcode.status",
32
+ "duration",
33
+ "pictures.base_link"
34
+ ].join(",");
35
+ const HOSTNAME_RE = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
36
+ const VIDEO_ID_RE = /^\d{1,20}$/;
37
+ const HASH_RE = /^[0-9a-f]{6,}$/i;
38
+ const FOLDER_URI_RE = /^\/users\/(\d{1,20})\/(?:projects|folders)\/(\d{1,20})$/;
39
+ const FOLDER_PATH_RE = /^\/user\/(\d{1,20})\/folders?\/(\d{1,20})\/?$/;
40
+ const FOLDER_FORMS = "/users/<owner id>/projects/<folder id> or https://vimeo.com/user/<owner id>/folder/<folder id>";
41
+ const videoSchema = z.object({
42
+ uri: z.string(),
43
+ name: z.string().nullish(),
44
+ link: z.string().nullish(),
45
+ player_embed_url: z.string().nullish(),
46
+ privacy: z.object({
47
+ view: z.string(),
48
+ embed: z.string()
49
+ }).partial().nullish(),
50
+ status: z.string().nullish(),
51
+ upload: z.object({ status: z.string().nullish() }).nullish(),
52
+ transcode: z.object({ status: z.string().nullish() }).nullish(),
53
+ duration: z.number().nullish(),
54
+ pictures: z.object({ base_link: z.string().nullish() }).nullish()
55
+ }).passthrough();
56
+ /** One page of videos in a folder. */
57
+ const folderPageSchema = z.object({
58
+ data: z.array(videoSchema).max(100),
59
+ paging: z.object({ next: z.string().nullish() }).nullish()
60
+ });
61
+ /** Fields that the tools read from a Vimeo folder. */
62
+ const FOLDER_FIELDS = "uri,name,link,manage_link,user.name";
63
+ /** One page of folders. */
64
+ const folderListSchema = z.object({
65
+ data: z.array(z.object({
66
+ uri: z.string().regex(FOLDER_URI_RE),
67
+ name: z.string().nullish(),
68
+ link: z.string().nullish(),
69
+ manage_link: z.string().nullish(),
70
+ user: z.object({ name: z.string().nullish() }).nullish()
71
+ })).max(100),
72
+ paging: z.object({ next: z.string().nullish() }).nullish()
73
+ });
74
+ /** Upload attempt for a new video or a new file version. */
75
+ const uploadAttemptSchema = z.object({
76
+ uri: z.string().optional(),
77
+ upload: z.object({ upload_link: z.string().url() })
78
+ });
79
+ /** Result fields of one video. */
80
+ const videoFields = {
81
+ video_id: z.string(),
82
+ name: z.string().optional(),
83
+ hash: z.string().optional(),
84
+ embed_url: z.string(),
85
+ link: z.string().optional(),
86
+ view: z.string().optional(),
87
+ embed: z.string().optional(),
88
+ upload_status: z.string().optional(),
89
+ transcode_status: z.string().optional(),
90
+ ready: z.boolean(),
91
+ duration_seconds: z.number().optional(),
92
+ thumbnail_url: z.string().optional()
93
+ };
94
+ /** Output of the tools that return one video. */
95
+ const videoOutputSchema = pluginToolOutputSchema.extend(videoFields);
96
+ /** Numeric Vimeo video ID. */
97
+ const videoIdSchema = z.string().trim().regex(VIDEO_ID_RE, "Use the numeric Vimeo video ID").describe("Numeric Vimeo video ID, such as the one vimeo_upload returned.");
98
+ /** Bare hostname where a video may be embedded. */
99
+ const embedDomainSchema = z.string().trim().toLowerCase().regex(HOSTNAME_RE, "Use a bare hostname, such as www.example.com");
100
+ /** Sandbox path of a file that a tool reads. */
101
+ const sandboxPathSchema = (what) => z.string().trim().min(1).describe(`Sandbox path of the ${what}.`);
102
+ /** Owner and canonical URI of a Vimeo folder URI or web link, or undefined. */
103
+ function parseFolder(value) {
104
+ const match = FOLDER_URI_RE.exec(value) ?? folderPathMatch(value);
105
+ if (!match) return void 0;
106
+ return {
107
+ owner: match[1],
108
+ uri: `/users/${match[1]}/projects/${match[2]}`
109
+ };
110
+ }
111
+ function folderPathMatch(value) {
112
+ if (!URL.canParse(value)) return null;
113
+ const url = new URL(value);
114
+ if (url.protocol !== "https:") return null;
115
+ if (url.hostname !== "vimeo.com" && url.hostname !== "www.vimeo.com") return null;
116
+ return FOLDER_PATH_RE.exec(url.pathname);
117
+ }
118
+ /** A Vimeo folder that a tool call names. */
119
+ const folderSchema = z.string().trim().refine((value) => parseFolder(value) !== void 0, `Use ${FOLDER_FORMS}`).describe(`Vimeo folder, as ${FOLDER_FORMS}. vimeo_listFolders lists the folders the account can reach.`);
120
+ /** Embed domains from input, else the install's default domains. */
121
+ function resolveEmbedDomains(input, settings) {
122
+ if (input) return input;
123
+ if (settings.embedDomains.length === 0) throw new PluginToolInputError("The install sets no default embed domains. Pass the hostnames where the video may be embedded.");
124
+ return settings.embedDomains;
125
+ }
126
+ /** Reach the Vimeo API through plugin egress for one operation. */
127
+ function vimeoClient(egress, operation, signal) {
128
+ const api = async (method, route, body) => {
129
+ const headers = { Accept: "application/vnd.vimeo.*+json;version=3.4" };
130
+ const init = {
131
+ method,
132
+ headers,
133
+ redirect: "error"
134
+ };
135
+ if (body !== void 0) {
136
+ headers["Content-Type"] = "application/json";
137
+ init.body = JSON.stringify(body);
138
+ }
139
+ if (signal) init.signal = signal;
140
+ const response = await egress.fetch({
141
+ operation,
142
+ provider: "vimeo",
143
+ request: new Request(`${API}${route}`, init)
144
+ });
145
+ if (!response.ok) {
146
+ const message = `Vimeo ${method} ${route} failed with HTTP ${response.status}: ${await errorDetail(response)}`;
147
+ if ([
148
+ 400,
149
+ 403,
150
+ 404
151
+ ].includes(response.status)) throw new PluginToolInputError(`${message}. Check the IDs and the folder.`);
152
+ throw new Error(message);
153
+ }
154
+ return response.status === 204 ? void 0 : response.json();
155
+ };
156
+ return {
157
+ api,
158
+ getVideo: async (id) => videoSchema.parse(await api("GET", `/videos/${id}?fields=${VIDEO_FIELDS}`))
159
+ };
160
+ }
161
+ async function errorDetail(response) {
162
+ const text = await response.text().catch(() => "");
163
+ const parsed = z.object({
164
+ error: z.string().optional(),
165
+ developer_message: z.string().optional()
166
+ }).safeParse(safeJson(text));
167
+ return (parsed.success ? [parsed.data.error, parsed.data.developer_message].filter(Boolean).join(" ") : "") || text.slice(0, 300);
168
+ }
169
+ function safeJson(text) {
170
+ try {
171
+ return JSON.parse(text);
172
+ } catch {
173
+ return;
174
+ }
175
+ }
176
+ /** Vimeo video ID from a URI such as `/videos/123`. */
177
+ function videoIdFromUri(uri) {
178
+ const id = uri.split("/").pop() ?? "";
179
+ if (!VIDEO_ID_RE.test(id)) throw new Error(`Vimeo returned an unexpected video URI: ${uri}`);
180
+ return id;
181
+ }
182
+ /**
183
+ * Privacy hash of an unlisted video. Vimeo puts it in the `h` query param of
184
+ * the player URL and in the last path segment of `vimeo.com/<id>/<hash>`.
185
+ */
186
+ function videoHash(video, id) {
187
+ if (video.player_embed_url) {
188
+ const h = new URL(video.player_embed_url).searchParams.get("h");
189
+ if (h && HASH_RE.test(h)) return h;
190
+ }
191
+ if (video.link) {
192
+ const [first, second] = new URL(video.link).pathname.split("/").filter(Boolean);
193
+ if (first === id && second && HASH_RE.test(second)) return second;
194
+ }
195
+ }
196
+ /** Select the result fields of one video. */
197
+ function describeVideo(video) {
198
+ const id = videoIdFromUri(video.uri);
199
+ const hash = videoHash(video, id);
200
+ const transcodeStatus = video.transcode?.status ?? void 0;
201
+ return {
202
+ video_id: id,
203
+ name: video.name ?? void 0,
204
+ hash,
205
+ embed_url: `https://player.vimeo.com/video/${id}${hash ? `?h=${hash}` : ""}`,
206
+ link: video.link ?? void 0,
207
+ view: video.privacy?.view,
208
+ embed: video.privacy?.embed,
209
+ upload_status: video.upload?.status ?? void 0,
210
+ transcode_status: transcodeStatus,
211
+ ready: transcodeStatus === "complete" || video.status === "available",
212
+ duration_seconds: video.duration || void 0,
213
+ thumbnail_url: video.pictures?.base_link ?? void 0
214
+ };
215
+ }
216
+ // src/settings.ts
217
+ /**
218
+ * Install settings of the Vimeo plugin. The app passes them to
219
+ * `vimeoPlugin()` in its plugin module, and a bad value stops the app at
220
+ * start instead of failing a tool call later.
221
+ */
222
+ /** Validate the plugin options, so a bad value fails when the app starts. */
223
+ function vimeoSettings(options) {
224
+ const embedDomains = z.array(embedDomainSchema).max(10).safeParse(options.embedDomains ?? []);
225
+ if (!embedDomains.success) throw new Error(`vimeoPlugin embedDomains must be at most 10 bare hostnames, such as www.example.com.`);
226
+ return { embedDomains: embedDomains.data };
227
+ }
228
+ // src/tools/list-folder.ts
229
+ /** List the videos in one Vimeo folder. */
230
+ const vimeoListFolderTool = definePluginTool({
231
+ annotations: {
232
+ destructiveHint: false,
233
+ idempotentHint: true,
234
+ openWorldHint: true,
235
+ readOnlyHint: true
236
+ },
237
+ description: "List the videos in a Vimeo folder, newest first, 100 per page, with each video's title, ID, embed URL, and processing state. Use it to find an existing video by title.",
238
+ inputSchema: z.object({
239
+ folder: folderSchema,
240
+ page: z.number().int().min(1).max(100).default(1).describe("Page number. Default 1.")
241
+ }).strict(),
242
+ outputSchema: pluginToolOutputSchema.extend({
243
+ folder_uri: z.string(),
244
+ videos: z.array(z.object(videoFields)).max(100),
245
+ next_page: z.number().optional()
246
+ }),
247
+ async execute(input, options, ctx) {
248
+ const folder = parseFolder(input.folder);
249
+ const client = vimeoClient(ctx.egress, VIMEO_OPERATIONS.listFolder, options.signal);
250
+ const result = folderPageSchema.parse(await client.api("GET", `${folder.uri}/videos?fields=${VIDEO_FIELDS}&per_page=100&page=${input.page}&sort=date&direction=desc`));
251
+ return {
252
+ folder_uri: folder.uri,
253
+ videos: result.data.map(describeVideo),
254
+ next_page: result.paging?.next ? input.page + 1 : void 0
255
+ };
256
+ }
257
+ });
258
+ // src/tools/list-folders.ts
259
+ const ownerIdSchema = z.string().trim().regex(/^\d{1,20}$/, "Use the numeric Vimeo user ID of the team owner").describe("Numeric user ID of a Vimeo team owner, the number after vimeo.com/user/ in a team folder link. Lists the team folders that the account can reach. Omit to list the account's own folders.");
260
+ /** List the Vimeo folders that the connected account can reach. */
261
+ const vimeoListFoldersTool = definePluginTool({
262
+ annotations: {
263
+ destructiveHint: false,
264
+ idempotentHint: true,
265
+ openWorldHint: true,
266
+ readOnlyHint: true
267
+ },
268
+ description: "List the Vimeo folders that the connected account can reach, by name, 100 per page, with each folder's URI, name, owner, and vimeo.com link. Lists the account's own folders, or the folders of a Vimeo team that the account is on.",
269
+ inputSchema: z.object({
270
+ team_owner_id: ownerIdSchema.optional(),
271
+ page: z.number().int().min(1).max(100).default(1).describe("Page number. Default 1.")
272
+ }).strict(),
273
+ outputSchema: pluginToolOutputSchema.extend({
274
+ folders: z.array(z.object({
275
+ folder_uri: z.string(),
276
+ name: z.string().optional(),
277
+ owner_id: z.string(),
278
+ owner_name: z.string().optional(),
279
+ link: z.string().optional()
280
+ })).max(100),
281
+ next_page: z.number().optional()
282
+ }),
283
+ async execute(input, options, ctx) {
284
+ const client = vimeoClient(ctx.egress, VIMEO_OPERATIONS.listFolders, options.signal);
285
+ const owner = input.team_owner_id ? `/users/${input.team_owner_id}` : "/me";
286
+ const result = folderListSchema.parse(await client.api("GET", `${owner}/projects?fields=${FOLDER_FIELDS}&per_page=100&page=${input.page}&sort=name&direction=asc`));
287
+ return {
288
+ folders: result.data.map((folder) => {
289
+ const { owner, uri } = parseFolder(folder.uri);
290
+ return {
291
+ folder_uri: uri,
292
+ name: folder.name ?? void 0,
293
+ owner_id: owner,
294
+ owner_name: folder.user?.name ?? void 0,
295
+ link: folder.manage_link ?? folder.link ?? void 0
296
+ };
297
+ }),
298
+ next_page: result.paging?.next ? input.page + 1 : void 0
299
+ };
300
+ }
301
+ });
302
+ // src/tool-support/media.ts
303
+ /**
304
+ * Read media files from the sandbox and send them to Vimeo upload links.
305
+ *
306
+ * The tools hold the whole file in memory, so the size caps stay small.
307
+ * Upload links are one-time URLs that Vimeo returns from an authenticated
308
+ * call, so they need no token.
309
+ */
310
+ const MAX_VIDEO_BYTES = 209715200;
311
+ const MAX_IMAGE_BYTES = 10485760;
312
+ /** Bytes per tus PATCH request. */
313
+ const CHUNK_BYTES = 8388608;
314
+ /** Failed tries per chunk before the upload stops. */
315
+ const MAX_CHUNK_RETRIES = 3;
316
+ const ascii = (bytes, start, end) => String.fromCharCode(...bytes.subarray(start, end));
317
+ /** MP4, QuickTime, or WebM, by magic bytes. */
318
+ function isVideo(bytes) {
319
+ const ftyp = bytes.length > 8 && ascii(bytes, 4, 8) === "ftyp";
320
+ const webm = bytes.length > 4 && bytes[0] === 26 && bytes[1] === 69 && bytes[2] === 223 && bytes[3] === 163;
321
+ return ftyp || webm;
322
+ }
323
+ /** Content type of a JPEG or PNG, by magic bytes. */
324
+ function imageType(bytes) {
325
+ if (bytes.length > 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "image/jpeg";
326
+ if (bytes.length > 8 && bytes[0] === 137 && ascii(bytes, 1, 4) === "PNG") return "image/png";
327
+ }
328
+ /**
329
+ * Read one sandbox file that `accepts` recognizes. Only media files qualify,
330
+ * so the tools cannot send other sandbox files out.
331
+ */
332
+ async function readMediaFile(input, sandbox, maxBytes, accepts, kind) {
333
+ const bytes = await sandbox.readFile(path.posix.resolve(sandbox.root, input));
334
+ if (!bytes) throw new PluginToolInputError(`${input} does not exist in the sandbox.`);
335
+ if (bytes.byteLength === 0 || bytes.byteLength > maxBytes) throw new PluginToolInputError(`${input} is ${bytes.byteLength} bytes. It must be 1 byte to ${maxBytes} bytes.`);
336
+ if (!accepts(bytes)) throw new PluginToolInputError(`${input} is not ${kind}.`);
337
+ return bytes;
338
+ }
339
+ /** Read an MP4, MOV, or WebM video from the sandbox. */
340
+ function readVideo(input, sandbox) {
341
+ return readMediaFile(input, sandbox, MAX_VIDEO_BYTES, isVideo, "an MP4, MOV, or WebM video");
342
+ }
343
+ /** Read a JPEG or PNG image from the sandbox. */
344
+ function readImage(input, sandbox) {
345
+ return readMediaFile(input, sandbox, MAX_IMAGE_BYTES, (bytes) => imageType(bytes) !== void 0, "a JPEG or PNG image");
346
+ }
347
+ /** Server offset of a tus upload. */
348
+ async function tusOffset(uploadLink, signal) {
349
+ const init = {
350
+ method: "HEAD",
351
+ headers: { "Tus-Resumable": "1.0.0" }
352
+ };
353
+ if (signal) init.signal = signal;
354
+ const response = await fetch(uploadLink, init);
355
+ const offset = Number(response.headers.get("Upload-Offset"));
356
+ if (!response.ok || !Number.isInteger(offset)) throw new Error(`Vimeo tus HEAD failed with HTTP ${response.status}`);
357
+ return offset;
358
+ }
359
+ /**
360
+ * Send the bytes to a tus upload link in chunks. After a failed chunk, ask
361
+ * the server for its offset and resume from there.
362
+ */
363
+ async function tusUpload(uploadLink, bytes, signal) {
364
+ let offset = 0;
365
+ let retries = 0;
366
+ while (offset < bytes.byteLength) {
367
+ const chunk = bytes.subarray(offset, Math.min(offset + CHUNK_BYTES, bytes.byteLength));
368
+ const init = {
369
+ method: "PATCH",
370
+ headers: {
371
+ "Tus-Resumable": "1.0.0",
372
+ "Upload-Offset": String(offset),
373
+ "Content-Type": "application/offset+octet-stream"
374
+ },
375
+ body: new Uint8Array(chunk)
376
+ };
377
+ if (signal) init.signal = signal;
378
+ try {
379
+ const response = await fetch(uploadLink, init);
380
+ const next = Number(response.headers.get("Upload-Offset"));
381
+ if (response.status !== 204 || !Number.isInteger(next) || next <= offset) throw new Error(`Vimeo tus PATCH failed with HTTP ${response.status}`);
382
+ offset = next;
383
+ retries = 0;
384
+ } catch (error) {
385
+ if (signal?.aborted || retries >= MAX_CHUNK_RETRIES) throw error;
386
+ retries += 1;
387
+ offset = await tusOffset(uploadLink, signal);
388
+ }
389
+ }
390
+ }
391
+ // src/tools/replace-file.ts
392
+ /** Replace the file of an existing Vimeo video. */
393
+ const vimeoReplaceFileTool = definePluginTool({
394
+ annotations: {
395
+ destructiveHint: true,
396
+ idempotentHint: false,
397
+ openWorldHint: true,
398
+ readOnlyHint: false
399
+ },
400
+ description: "Replace the file of a Vimeo video with a new render from the sandbox. The video keeps its ID, hash, privacy, and embed domains, so links to it need no change. Vimeo processes the new file in the background.",
401
+ describeProposal: (input) => `Replace the file of Vimeo video ${input.video_id} with ${input.path}`,
402
+ inputSchema: z.object({
403
+ video_id: videoIdSchema,
404
+ path: sandboxPathSchema("new MP4, MOV, or WebM file")
405
+ }).strict(),
406
+ outputSchema: videoOutputSchema.extend({ bytes: z.number() }),
407
+ async execute(input, options, ctx) {
408
+ const bytes = await readVideo(input.path, ctx.sandbox);
409
+ const signal = options.signal;
410
+ const client = vimeoClient(ctx.egress, VIMEO_OPERATIONS.replaceFile, signal);
411
+ await tusUpload(uploadAttemptSchema.parse(await client.api("POST", `/videos/${input.video_id}/versions?fields=upload`, {
412
+ file_name: path.posix.basename(input.path),
413
+ upload: {
414
+ status: "in_progress",
415
+ approach: "tus",
416
+ size: String(bytes.byteLength)
417
+ }
418
+ })).upload.upload_link, bytes, signal);
419
+ return {
420
+ ...describeVideo(await client.getVideo(input.video_id)),
421
+ bytes: bytes.byteLength
422
+ };
423
+ }
424
+ });
425
+ // src/tools/set-thumbnail.ts
426
+ const pictureSchema = z.object({
427
+ uri: z.string(),
428
+ link: z.string().url(),
429
+ base_link: z.string().nullish()
430
+ });
431
+ /** Set a Vimeo video's thumbnail from a sandbox image. */
432
+ const vimeoSetThumbnailTool = definePluginTool({
433
+ annotations: {
434
+ destructiveHint: false,
435
+ idempotentHint: false,
436
+ openWorldHint: true,
437
+ readOnlyHint: false
438
+ },
439
+ description: "Set the poster thumbnail of a Vimeo video from a JPEG or PNG in the sandbox. The new image replaces the active thumbnail.",
440
+ describeProposal: (input) => `Set the thumbnail of Vimeo video ${input.video_id} from ${input.path}`,
441
+ inputSchema: z.object({
442
+ video_id: videoIdSchema,
443
+ path: sandboxPathSchema("JPEG or PNG poster image")
444
+ }).strict(),
445
+ outputSchema: pluginToolOutputSchema.extend({
446
+ video_id: z.string(),
447
+ picture_uri: z.string(),
448
+ thumbnail_url: z.string().optional()
449
+ }),
450
+ async execute(input, options, ctx) {
451
+ const bytes = await readImage(input.path, ctx.sandbox);
452
+ const signal = options.signal;
453
+ const client = vimeoClient(ctx.egress, VIMEO_OPERATIONS.setThumbnail, signal);
454
+ const picture = pictureSchema.parse(await client.api("POST", `/videos/${input.video_id}/pictures`));
455
+ const init = {
456
+ method: "PUT",
457
+ headers: { "Content-Type": imageType(bytes) },
458
+ body: new Uint8Array(bytes)
459
+ };
460
+ if (signal) init.signal = signal;
461
+ const response = await fetch(picture.link, init);
462
+ if (!response.ok) throw new Error(`Vimeo thumbnail upload failed with HTTP ${response.status}`);
463
+ const active = pictureSchema.partial({ link: true }).parse(await client.api("PATCH", picture.uri, { active: true }));
464
+ return {
465
+ video_id: input.video_id,
466
+ picture_uri: picture.uri,
467
+ thumbnail_url: active.base_link ?? picture.base_link ?? void 0
468
+ };
469
+ }
470
+ });
471
+ // src/tools/status.ts
472
+ /** Read a Vimeo video's processing state and embed URL. */
473
+ const vimeoStatusTool = definePluginTool({
474
+ annotations: {
475
+ destructiveHint: false,
476
+ idempotentHint: true,
477
+ openWorldHint: true,
478
+ readOnlyHint: true
479
+ },
480
+ description: "Get the processing state, privacy, and embed URL of a Vimeo video. `ready` is true when Vimeo finished transcoding and the embed plays.",
481
+ inputSchema: z.object({ video_id: videoIdSchema }).strict(),
482
+ outputSchema: videoOutputSchema,
483
+ async execute(input, options, ctx) {
484
+ return describeVideo(await vimeoClient(ctx.egress, VIMEO_OPERATIONS.status, options.signal).getVideo(input.video_id));
485
+ }
486
+ });
487
+ // src/tools/upload.ts
488
+ /** Upload a sandbox video into a Vimeo folder as a private video. */
489
+ function vimeoUploadTool(settings) {
490
+ return definePluginTool({
491
+ annotations: {
492
+ destructiveHint: false,
493
+ idempotentHint: false,
494
+ openWorldHint: true,
495
+ readOnlyHint: false
496
+ },
497
+ description: "Upload a video file from the sandbox into a Vimeo folder as a private video: hidden from vimeo.com or unlisted, embeddable only on allowed domains, not downloadable. Returns the video ID, the privacy hash for unlisted videos, and the embed URL once the bytes are sent; Vimeo finishes processing later. Each call creates a new video. To change the file of an existing video, use vimeo_replaceFile.",
498
+ describeProposal: (input) => `Upload ${input.path} to Vimeo folder ${input.folder} as "${input.title}" (${input.view ?? "disable"}, embeds on ${(input.embed_domains ?? settings.embedDomains).join(", ") || "no domain"})`,
499
+ inputSchema: z.object({
500
+ path: sandboxPathSchema("MP4, MOV, or WebM file to upload"),
501
+ folder: folderSchema,
502
+ title: z.string().trim().min(1).max(128).describe("Video title."),
503
+ description: z.string().trim().max(5e3).describe("Video description. Omit for none.").optional(),
504
+ view: z.enum(["disable", "unlisted"]).default("disable").describe("Who can watch on vimeo.com. `disable` (default) hides the video from vimeo.com, so it plays only in embeds. `unlisted` also gives a vimeo.com link for anyone who has it."),
505
+ embed_domains: z.array(embedDomainSchema).min(1).max(10).describe("Hostnames where the video may be embedded. Omit to use the install's default domains.").optional()
506
+ }).strict(),
507
+ outputSchema: videoOutputSchema.extend({
508
+ bytes: z.number(),
509
+ folder_uri: z.string(),
510
+ status_error: z.string().optional()
511
+ }),
512
+ async execute(input, options, ctx) {
513
+ const folder = parseFolder(input.folder);
514
+ const embedDomains = resolveEmbedDomains(input.embed_domains, settings);
515
+ const bytes = await readVideo(input.path, ctx.sandbox);
516
+ const signal = options.signal;
517
+ const client = vimeoClient(ctx.egress, VIMEO_OPERATIONS.upload, signal);
518
+ const created = uploadAttemptSchema.parse(await client.api("POST", `/users/${folder.owner}/videos?fields=uri,upload`, {
519
+ name: input.title,
520
+ description: input.description,
521
+ folder_uri: folder.uri,
522
+ upload: {
523
+ approach: "tus",
524
+ size: String(bytes.byteLength)
525
+ },
526
+ privacy: {
527
+ view: input.view,
528
+ embed: "whitelist",
529
+ download: false,
530
+ add: false,
531
+ comments: "nobody"
532
+ },
533
+ embed_domains: embedDomains
534
+ }));
535
+ const id = videoIdFromUri(created.uri ?? "");
536
+ try {
537
+ await tusUpload(created.upload.upload_link, bytes, signal);
538
+ } catch (error) {
539
+ throw new Error(`Vimeo video ${id} was created, but the upload did not finish: ${String(error)}`, { cause: error });
540
+ }
541
+ const uploaded = {
542
+ bytes: bytes.byteLength,
543
+ folder_uri: folder.uri
544
+ };
545
+ try {
546
+ return {
547
+ ...describeVideo(await client.getVideo(id)),
548
+ ...uploaded
549
+ };
550
+ } catch (error) {
551
+ return {
552
+ video_id: id,
553
+ embed_url: `https://player.vimeo.com/video/${id}`,
554
+ ready: false,
555
+ ...uploaded,
556
+ status_error: `The upload finished, but reading the video failed: ${String(error)}. Call vimeo_status for the hash and state; do not upload again.`
557
+ };
558
+ }
559
+ }
560
+ });
561
+ }
562
+ // src/index.ts
563
+ /**
564
+ * Vimeo plugin runtime boundary.
565
+ *
566
+ * The tools list the Vimeo folders the account can reach, upload sandbox
567
+ * videos into the folder that each call names as private videos, replace
568
+ * their files and thumbnails, and read their state. They run on the
569
+ * host and send files with tus in chunks, so sandbox request limits do not
570
+ * apply. Junior uses only the plugin's service account: an admin connects
571
+ * one shared Vimeo account, and people never connect their own. Junior adds
572
+ * its token to the plugin's API calls on the host.
573
+ *
574
+ * Every upload is private when Vimeo creates it: hidden from vimeo.com or
575
+ * unlisted, embeddable only on allowed domains, and not downloadable. No
576
+ * tool can make a video public.
577
+ */
578
+ /** Register the Vimeo upload, file, thumbnail, status, and folder tools. */
579
+ function vimeoPlugin(options = {}) {
580
+ const settings = vimeoSettings(options);
581
+ return defineJuniorPlugin({
582
+ packageName: "@sentry/junior-vimeo",
583
+ manifest: {
584
+ name: "vimeo",
585
+ displayName: "Vimeo",
586
+ description: "Upload private videos to Vimeo folders, replace their files and thumbnails, and check their processing",
587
+ credentials: {
588
+ type: "oauth-bearer",
589
+ domains: ["api.vimeo.com"]
590
+ },
591
+ oauth: {
592
+ clientIdEnv: "VIMEO_CLIENT_ID",
593
+ clientSecretEnv: "VIMEO_CLIENT_SECRET",
594
+ authorizeEndpoint: "https://api.vimeo.com/oauth/authorize",
595
+ tokenEndpoint: "https://api.vimeo.com/oauth/access_token",
596
+ scope: "public private upload edit",
597
+ tokenAuthMethod: "basic"
598
+ },
599
+ accounts: {
600
+ userOAuth: false,
601
+ serviceAccount: { operations: Object.values(VIMEO_OPERATIONS) }
602
+ },
603
+ envVars: {
604
+ VIMEO_CLIENT_ID: {},
605
+ VIMEO_CLIENT_SECRET: {}
606
+ }
607
+ },
608
+ hooks: { tools() {
609
+ return {
610
+ upload: vimeoUploadTool(settings),
611
+ replaceFile: vimeoReplaceFileTool,
612
+ setThumbnail: vimeoSetThumbnailTool,
613
+ status: vimeoStatusTool,
614
+ listFolder: vimeoListFolderTool,
615
+ listFolders: vimeoListFoldersTool
616
+ };
617
+ } }
618
+ });
619
+ }
620
+ export { vimeoPlugin };
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@sentry/junior-vimeo",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.316.0",
4
+ "private": false,
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "type": "module",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/getsentry/junior.git",
12
+ "directory": "packages/junior-vimeo"
13
+ },
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "dependencies": {
24
+ "@sentry/junior-plugin-api": "0.316.0",
25
+ "zod": "^4.6.7"
26
+ },
27
+ "devDependencies": {
28
+ "@sentry/junior-testing": "0.0.0",
29
+ "@types/node": "^24.19.2",
30
+ "tsdown": "0.23.7",
31
+ "typescript": "7.0.2",
32
+ "vitest": "^4.1.12"
33
+ },
34
+ "scripts": {
35
+ "build": "tsdown",
36
+ "test": "vitest run",
37
+ "typecheck": "tsc --noEmit"
38
+ }
6
39
  }