apple-shortcuts-skill 0.0.0-stage → 1.0.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 zxc20057423
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,38 @@
1
- # Temporary Holding Version
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.
1
+ # apple-shortcuts-skill
2
+
3
+ 一個讓 AI agent **在沒有 Mac 的情況下,寫出真正能安裝的 Apple 捷徑**的 skill。
4
+
5
+ 大多數 agent 只能告訴你要在捷徑 App 裡點哪些按鈕。這個 skill 教的是完整流程:
6
+
7
+ 1. **設計** — 把工作流程寫成資料,而不是一步步點。其中一個關鍵技巧:用一串有順序的「取代文字(正規表示式)」動作,當作不用條件分支的 if/else 邏輯。
8
+ 2. **先測邏輯** — 組裝之前,先用 Python 把同一套規則拿真實輸入模擬跑過。
9
+ 3. **組裝** — 用 [`python-shortcuts`](https://pypi.org/project/python-shortcuts/) 產生未簽署的 `.shortcut`,包含函式庫缺少的「取代文字」動作,以及它沒做的 plist 後處理(分享頁類型、輸入類型、圖示)。
10
+ 4. **簽署** — iOS 15 之後,未簽署的 `.shortcut` 檔案會被拒絕,只跳一句「無法載入檔案」。簽署可以用 Mac(`shortcuts sign`),或遠端簽署服務如 [Shortcuty Sign](https://sign.shortcuty.app)、RoutineHub HubSign(上傳前必須先取得使用者同意 — agent 要先問)。
11
+ 5. **交付** — 交給使用者的必須是簽署完成的檔案(驗證開頭是 `AEA1` 魔術字節),使用者點一下就能安裝,再附一個具體的實機測試方式。
12
+
13
+ ## 內容
14
+
15
+ - [`SKILL.md`](SKILL.md) — skill 本體。放進你的 agent 的 skills 資料夾(Claude Code、Codex、Muse……),agent 就能照著做。
16
+ - [`tools/build_template.py`](tools/build_template.py) — 可重用的組裝模板:自訂「取代文字」動作、plist 後處理、組完自動回讀驗證動作清單。
17
+ - [`examples/open-in-apple-maps/`](examples/open-in-apple-maps/) — 完整實作範例:把 Google Maps 連結用 Apple 地圖開啟的分享頁捷徑。網路上流傳的原版會**開錯位置** — 它解析的是 `@緯度,經度`(地圖畫面中心),不是 `!3d…!4d…`(地點本身的釘點座標),而且沒有先展開短連結。範例含 `test_logic.py`,用 7 個案例模擬裝置上實際執行的同一套正規表示式鏈。
18
+
19
+ ## 快速開始
20
+
21
+ ```bash
22
+ cd examples/open-in-apple-maps
23
+ python3 test_logic.py # 7 個案例應該全過
24
+ python3 -m venv .venv
25
+ .venv/bin/pip install python-shortcuts
26
+ .venv/bin/python build.py # 產出未簽署的 .shortcut
27
+ # 接著簽署(見 SKILL.md 第 4 步),再把檔案傳到 iPhone
28
+ ```
29
+
30
+ ## 需求
31
+
32
+ - Python 3.10+
33
+ - `python-shortcuts`(pip)
34
+ - 簽署方式三選一:有 Shortcuts 的 Mac、免帳號的遠端簽署服務、或從已有該捷徑的裝置產生 iCloud 分享連結。
35
+
36
+ ## 授權
37
+
38
+ MIT — 見 [`LICENSE`](LICENSE)。
package/SKILL.md ADDED
@@ -0,0 +1,128 @@
1
+ ---
2
+ name: apple-shortcuts-authoring
3
+ description: Author real, installable Apple Shortcuts (.shortcut files) from a Linux/Windows machine with no Mac — build the workflow programmatically, test the logic before building, sign the file so iOS will accept it, and deliver it ready to tap-and-install.
4
+ ---
5
+
6
+ # Apple Shortcuts Authoring (no Mac required)
7
+
8
+ Use this skill when the user wants you to **create or fix an iOS Shortcut for them**,
9
+ not just describe the taps. The end product is a signed `.shortcut` file the user
10
+ can tap on their iPhone and add directly.
11
+
12
+ ## The one fact everything depends on
13
+
14
+ Since iOS 15, **Shortcuts refuses unsigned `.shortcut` files**. An unsigned file
15
+ tapped on a modern iPhone fails with a generic "could not load file" error.
16
+ The old advice "enable Settings → Shortcuts → Allow Untrusted Shortcuts" is
17
+ **obsolete** — that toggle no longer exists. A file is importable only if it is:
18
+
19
+ - shared through an iCloud link from a real Shortcuts app, or
20
+ - a signed file (AEA1 container) produced by `shortcuts sign` on a Mac, or
21
+ - signed by a remote signing service (see Step 4).
22
+
23
+ So the pipeline is always: **build unsigned → sign → deliver**. Never send the
24
+ user an unsigned file and call it done; verify the signed artifact starts with
25
+ the `AEA1` magic bytes before delivering.
26
+
27
+ ## Step 1 — Design the workflow as data, not taps
28
+
29
+ Write the shortcut's logic as an ordered list of actions. Prefer designs that
30
+ avoid fragile control flow when a chain of transforms can do the job:
31
+
32
+ - A chain of "Replace Text (regex)" actions is order-dependent in a useful way:
33
+ each rule rewrites the value only if it matches, otherwise the value passes
34
+ through unchanged. Put the most specific / most authoritative extraction
35
+ first, fallbacks after. This gives you if/else behaviour with zero
36
+ conditional actions to serialize.
37
+ - Test the transform chain in plain Python (`re.sub` with the same patterns)
38
+ against a table of realistic inputs **before** building anything. Regex
39
+ dialect differences (ICU on device vs Python) are small for the patterns
40
+ used here; the simulation catches ordering and greediness bugs, which are
41
+ the ones that actually bite.
42
+
43
+ ## Step 2 — Build the unsigned `.shortcut`
44
+
45
+ Use the `python-shortcuts` package (`pip install python-shortcuts`) to emit a
46
+ binary plist `.shortcut`. Practical notes learned the hard way:
47
+
48
+ - The library covers common actions (Text, Open URL, Expand URL, URL
49
+ Encode/Decode, Set Variable, Comment, …) but **lacks Match/Replace Text**.
50
+ Add it as a custom action class — see `tools/build_template.py`:
51
+ identifier `is.workflow.actions.text.replace`, parameters
52
+ `WFReplaceTextFind`, `WFReplaceTextReplace`, `WFReplaceTextCaseSensitive`,
53
+ `WFReplaceTextRegularExpression`.
54
+ - URL Encode/Decode serialize as `is.workflow.actions.urlencode` with
55
+ `WFEncodeMode` = `Encode`/`Decode`. iOS migrates this legacy identifier
56
+ fine.
57
+ - Reference a named variable inside a Text action with `{{variableName}}`
58
+ (the library converts it to the object-replacement-character attachment
59
+ format Shortcuts expects).
60
+ - `plistlib.Data` was removed in Python 3.12; if the library's icon dump
61
+ crashes, monkey-patch `Shortcut._get_icon` and set the icon yourself in
62
+ post-processing.
63
+ - Post-process the plist before saving:
64
+ - `WFWorkflowTypes = ['ActionExtension']` if the shortcut should appear in
65
+ the Share Sheet (the library defaults to widget/watch types).
66
+ - `WFWorkflowInputContentItemClasses` — e.g. `WFURLContentItem`,
67
+ `WFTextContentItem`, `WFWebPageContentItem`, `WFSafariWebPageContentItem`,
68
+ `WFLocationContentItem`, as appropriate.
69
+ - `WFWorkflowIcon` — `WFWorkflowIconStartColor` / `WFWorkflowIconEndColor`
70
+ (ARGB int) and `WFWorkflowIconGlyphNumber`.
71
+ - The **file name becomes the shortcut's name** on import. Name the file
72
+ exactly what the shortcut should be called.
73
+ - Always reload the produced plist and print the action list to verify count,
74
+ order, and parameters before moving on.
75
+
76
+ ## Step 3 — Inspect an existing shared shortcut (when fixing one)
77
+
78
+ An iCloud share link `https://www.icloud.com/shortcuts/<id>` exposes metadata:
79
+
80
+ ```
81
+ GET https://www.icloud.com/shortcuts/api/records/<ID>
82
+ ```
83
+
84
+ The JSON gives the shortcut's `name`, icon glyph/color, `signingStatus`, and a
85
+ `downloadURL` for the signed file. The signed file is an AEA1 archive — you
86
+ generally **cannot** extract the workflow plist from it without Apple's keys,
87
+ and the public share page shows no action list. So when fixing someone else's
88
+ shortcut: identify it from the metadata, diagnose from the *symptom* and the
89
+ input format (ask the user what they feed it and what goes wrong), and rebuild
90
+ a corrected equivalent rather than promising to patch the original binary.
91
+
92
+ ## Step 4 — Sign it (ask the user first)
93
+
94
+ Signing requires sending the file to a third party if you have no Mac. The
95
+ file contains only the generic actions you wrote — but still **tell the user
96
+ which service you will upload to and get their OK first**.
97
+
98
+ Working options (as of 2026-11):
99
+
100
+ - **Shortcuty Sign** — https://sign.shortcuty.app — upload unsigned file,
101
+ download the signed copy. Files are only kept while being signed.
102
+ - **RoutineHub HubSign** — RoutineHub's signing tool, also used by the Cherri
103
+ toolchain (`cherri --hubsign`).
104
+ - A Mac you control: `shortcuts sign --mode anyone --input in.shortcut
105
+ --output out.shortcut`.
106
+
107
+ Verify the result: signed files are visibly larger (signature + certificates)
108
+ and start with the bytes `AEA1`.
109
+
110
+ ## Step 5 — Deliver and verify on device
111
+
112
+ - Deliver the **signed** file as an attachment with the exact final name.
113
+ - Warn the user to delete any earlier unsigned copy from Files first, so they
114
+ don't tap the wrong one.
115
+ - Give one concrete test: a real input they would actually use, the expected
116
+ result, and "send me a screenshot / the input if it's still wrong" — then
117
+ debug from their actual failing input, not from guesses.
118
+
119
+ ## Worked example
120
+
121
+ `examples/open-in-apple-maps/` is a complete, real build: a Share Sheet
122
+ shortcut that opens Google Maps links in Apple Maps. Its original version
123
+ opened the wrong place because it parsed the `@lat,lng` viewport centre from
124
+ Google URLs instead of the `!3d<lat>!4d<lng>` pin coordinates, and never
125
+ expanded `maps.app.goo.gl` short links. The fixed build is a 17-action
126
+ no-conditional chain: expand → decode → pin coords → viewport coords →
127
+ ll/center/viewpoint params → place name → q/query/destination params →
128
+ cleanup → encode → open `https://maps.apple.com/?q=…`.
package/bin/install.js ADDED
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Install the apple-shortcuts-authoring skill into an agent skills folder.
4
+ *
5
+ * npx apple-shortcuts-skill # -> ~/.claude/skills/apple-shortcuts-authoring
6
+ * npx apple-shortcuts-skill <target-dir> # -> <target-dir>
7
+ *
8
+ * Copies SKILL.md, tools/ and examples/ from this package. No dependencies.
9
+ */
10
+ const fs = require("fs");
11
+ const os = require("os");
12
+ const path = require("path");
13
+
14
+ const target = process.argv[2]
15
+ ? path.resolve(process.argv[2])
16
+ : path.join(os.homedir(), ".claude", "skills", "apple-shortcuts-authoring");
17
+
18
+ const pkgRoot = path.join(__dirname, "..");
19
+ const items = ["SKILL.md", "tools", "examples"];
20
+
21
+ fs.mkdirSync(target, { recursive: true });
22
+ for (const item of items) {
23
+ fs.cpSync(path.join(pkgRoot, item), path.join(target, item), {
24
+ recursive: true,
25
+ force: true,
26
+ });
27
+ }
28
+ console.log(`apple-shortcuts-authoring skill installed to: ${target}`);
@@ -0,0 +1,30 @@
1
+ # 範例:在 Apple 地圖開啟
2
+
3
+ 一支分享頁捷徑:把任何 Google Maps 連結(或一段地址)分享給它,同一個地點就會用 Apple 地圖打開。
4
+
5
+ ## 為什麼常見的版本是壞的
6
+
7
+ Google Maps 的地點連結裡有**兩組**座標:
8
+
9
+ | 座標 | 意義 |
10
+ | --- | --- |
11
+ | `@24.1560,120.6630` | 複製連結當下**地圖畫面的中心** — 使用者滑過地圖就會跟著跑掉 |
12
+ | `!3d24.1234!4d120.5678` | **地點本身的釘點** |
13
+
14
+ 流傳的捷徑解析的是 `@` 那組(或者拿到沒展開的 `maps.app.goo.gl` 短連結,什麼都解析不到),所以 Apple 地圖打開的是「附近,但不是那個地方」。
15
+
16
+ ## 修法(17 個動作,零條件分支)
17
+
18
+ 1. **展開 URL** — 先把短連結還原。
19
+ 2. **URL 解碼** — 讓 `%2C` 逗號和百分比編碼的地名能乾淨解析。
20
+ 3. 一串有順序的**取代文字(正規表示式)**,每條只在符合時才改寫:釘點座標 → 畫面中心座標 → `ll`/`center`/`sll` → `viewpoint` → `q=loc:` 座標 → `/place/<地名>` → `q` → `query` → `destination` → 去掉 `loc:` → `+` 換成空白。
21
+ 4. 把結果 **URL 編碼**,組成 `https://maps.apple.com/?q=<結果>`,**開啟 URL**。用 `q=` 搜尋對座標和地名都成立,這正是這個設計可以不用條件分支的原因。
22
+
23
+ ## 檔案
24
+
25
+ - `build.py` — 組裝未簽署的 `.shortcut`(圖示與名稱與它取代的原版捷徑相同)。
26
+ - `test_logic.py` — 用 Python 模擬同一套規則鏈;7 個案例涵蓋釘點 vs. 畫面中心、文字/座標搜尋網址、導航、`ll` 參數和純地址。每次組裝前先跑它。
27
+
28
+ ## 安裝
29
+
30
+ 組裝 → 簽署(見 repo 的 `SKILL.md` 第 4 步)→ 把簽好的檔案傳到 iPhone → 點開 →「加入捷徑」。之後把任何 Google Maps 地點分享給它,確認 Apple 地圖落在地點本尊上。
@@ -0,0 +1,69 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Build "在 Apple 地圖開啟" (Open in Apple Maps) — a Share Sheet shortcut that
4
+ takes a Google Maps link and opens the same place in Apple Maps.
5
+
6
+ Fixes vs. the common broken version:
7
+ 1. Expands short links (maps.app.goo.gl) before parsing.
8
+ 2. Prefers the place pin coordinates (!3d<lat>!4d<lng>) over the
9
+ @<lat>,<lng> viewport centre, which is what made the old one open
10
+ "nearby, but not the place".
11
+ 3. Falls back to place name / q / query / destination search terms.
12
+
13
+ Run test_logic.py first — it simulates this exact regex chain in Python.
14
+
15
+ python3 -m venv .venv && .venv/bin/pip install python-shortcuts
16
+ .venv/bin/python build.py # writes the unsigned .shortcut
17
+
18
+ The output is UNSIGNED: sign it before installing on iOS >= 15 (SKILL.md).
19
+ """
20
+ import os
21
+ import sys
22
+
23
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "tools"))
24
+ from build_template import build, rep # noqa: E402
25
+
26
+ from shortcuts.actions import ( # noqa: E402
27
+ CommentAction,
28
+ ExpandURLAction,
29
+ OpenURLAction,
30
+ SetVariableAction,
31
+ TextAction,
32
+ URLDecodeAction,
33
+ URLEncodeAction,
34
+ )
35
+
36
+ NAME = "在 Apple 地圖開啟"
37
+
38
+ ACTIONS = [
39
+ CommentAction(
40
+ data={
41
+ "text": "Expand the short link and decode first; coordinates prefer "
42
+ "the place pin (!3d/!4d) over the @ viewport centre; "
43
+ "fall back to name/address search."
44
+ }
45
+ ),
46
+ ExpandURLAction(),
47
+ URLDecodeAction(),
48
+ # --- coordinate extraction, most authoritative first ---
49
+ rep(r".*!3d(-?[0-9.]+)!4d(-?[0-9.]+).*", "$1,$2"), # place pin
50
+ rep(r".*@(-?[0-9.]+),(-?[0-9.]+).*", "$1,$2"), # viewport centre
51
+ rep(r".*[?&](ll|center|sll)=(-?[0-9.]+),(-?[0-9.]+).*", "$2,$3"),
52
+ rep(r".*[?&]viewpoint=(-?[0-9.]+),(-?[0-9.]+).*", "$1,$2"),
53
+ rep(r".*[?&]q=loc:(-?[0-9.]+),(-?[0-9.]+).*", "$1,$2"),
54
+ # --- text fallbacks ---
55
+ rep(r".*/place/([^/]+).*", "$1"), # place name
56
+ rep(r".*[?&]q=([^&]+).*", "$1"),
57
+ rep(r".*[?&]query=([^&]+).*", "$1"),
58
+ rep(r".*[?&]destination=([^&]+).*", "$1"),
59
+ rep(r"^loc:", ""),
60
+ rep(r"\+", " "),
61
+ # --- open in Apple Maps as a search (works for coords and names) ---
62
+ URLEncodeAction(),
63
+ SetVariableAction(data={"name": "appleQuery"}),
64
+ TextAction(data={"text": "https://maps.apple.com/?q={{appleQuery}}"}),
65
+ OpenURLAction(),
66
+ ]
67
+
68
+ if __name__ == "__main__":
69
+ build(NAME, ACTIONS, f"{NAME}.shortcut")
@@ -0,0 +1,67 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Simulate the shortcut's regex chain in Python before building anything.
4
+
5
+ The chain mirrors build.py action-for-action: each rule rewrites the value
6
+ only if it matches, otherwise the value passes through unchanged — the same
7
+ semantics as chained Replace Text actions in Shortcuts.
8
+
9
+ python3 test_logic.py
10
+ """
11
+ import re
12
+ from urllib.parse import unquote
13
+
14
+ STEPS = [
15
+ (r".*!3d(-?[0-9.]+)!4d(-?[0-9.]+).*", r"\1,\2"),
16
+ (r".*@(-?[0-9.]+),(-?[0-9.]+).*", r"\1,\2"),
17
+ (r".*[?&](?:ll|center|sll)=(-?[0-9.]+),(-?[0-9.]+).*", r"\1,\2"),
18
+ (r".*[?&]viewpoint=(-?[0-9.]+),(-?[0-9.]+).*", r"\1,\2"),
19
+ (r".*[?&]q=loc:(-?[0-9.]+),(-?[0-9.]+).*", r"\1,\2"),
20
+ (r".*/place/([^/]+).*", r"\1"),
21
+ (r".*[?&]q=([^&]+).*", r"\1"),
22
+ (r".*[?&]query=([^&]+).*", r"\1"),
23
+ (r".*[?&]destination=([^&]+).*", r"\1"),
24
+ (r"^loc:", ""),
25
+ (r"\+", " "),
26
+ ]
27
+
28
+
29
+ def chain(url: str) -> str:
30
+ value = unquote(url) # the shortcut URL-decodes right after expanding
31
+ for pattern, replacement in STEPS:
32
+ value = re.sub(pattern, replacement, value)
33
+ return value
34
+
35
+
36
+ TESTS = {
37
+ # pin coordinates must win over the viewport centre
38
+ "https://www.google.com/maps/place/%E5%8D%A1%E5%95%A1%E9%82%A3/@24.1560,120.6630,17z/data=!4m6!3m5!1s0x123!8m2!3d24.1234!4d120.5678":
39
+ "24.1234,120.5678",
40
+ # no pin segment -> viewport centre is the best available
41
+ "https://www.google.com/maps/place/Some+Shop/@25.0330,121.5654,18z/data=!4m6":
42
+ "25.0330,121.5654",
43
+ # text search URL
44
+ "https://www.google.com/maps/search/?api=1&query=%E5%8F%B0%E4%B8%AD%E5%B8%82%E5%A4%A7%E9%87%8C%E5%8D%80%E4%BB%81%E7%A6%8F%E8%A1%97":
45
+ "台中市大里區仁福街",
46
+ # coordinate search URL (percent-encoded comma)
47
+ "https://www.google.com/maps/search/?api=1&query=24.08%2C120.67":
48
+ "24.08,120.67",
49
+ # directions URL -> destination name
50
+ "https://www.google.com/maps/dir/?api=1&destination=%E9%84%B0%E9%95%B7%E5%81%9C%E8%BB%8A%E5%A0%B4":
51
+ "鄰長停車場",
52
+ # ll parameter
53
+ "https://maps.google.com/?ll=24.1500,120.6800&z=16":
54
+ "24.1500,120.6800",
55
+ # plain address passes through untouched
56
+ "台中市大里區仁福街100號":
57
+ "台中市大里區仁福街100號",
58
+ }
59
+
60
+ if __name__ == "__main__":
61
+ failed = 0
62
+ for url, expected in TESTS.items():
63
+ got = chain(url)
64
+ ok = got == expected
65
+ failed += not ok
66
+ print(f"{'PASS' if ok else 'FAIL'} {got!r}" + ("" if ok else f" (expected {expected!r})"))
67
+ raise SystemExit(1 if failed else 0)
package/package.json CHANGED
@@ -1,6 +1 @@
1
- {
2
- "name": "apple-shortcuts-skill",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {"author":"zxc20057423","bin":{"apple-shortcuts-skill":"bin/install.js"},"bugs":{"url":"https://github.com/zxc20057423/apple-shortcuts-skill/issues"},"description":"讓 AI agent 在沒有 Mac 的情況下,寫出真正能安裝的 Apple 捷徑(.shortcut):組裝、邏輯測試、簽署、交付。An AI-agent skill for authoring real, installable Apple Shortcuts with no Mac.","engines":{"node":">=18"},"files":["SKILL.md","README.md","LICENSE","tools","examples","bin"],"homepage":"https://github.com/zxc20057423/apple-shortcuts-skill#readme","keywords":["apple-shortcuts","ios-shortcuts","ai-agent","skill","automation","claude-code","codex"],"license":"MIT","name":"apple-shortcuts-skill","repository":{"type":"git","url":"git+https://github.com/zxc20057423/apple-shortcuts-skill.git"},"version":"1.0.0"}
@@ -0,0 +1,102 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Template for building an unsigned iOS .shortcut file with python-shortcuts.
4
+
5
+ Usage:
6
+ python3 -m venv .venv && .venv/bin/pip install python-shortcuts
7
+ .venv/bin/python tools/build_template.py "My Shortcut"
8
+
9
+ The output is UNSIGNED. iOS >= 15 will refuse it until it is signed
10
+ (see SKILL.md, Step 4). The file name becomes the shortcut's name on import.
11
+ """
12
+ import plistlib
13
+ import sys
14
+
15
+ from shortcuts import Shortcut
16
+ from shortcuts.actions import (
17
+ CommentAction,
18
+ ExpandURLAction,
19
+ OpenURLAction,
20
+ SetVariableAction,
21
+ TextAction,
22
+ URLDecodeAction,
23
+ URLEncodeAction,
24
+ )
25
+ from shortcuts.actions.base import BaseAction, BooleanField, Field
26
+
27
+
28
+ class ReplaceTextAction(BaseAction):
29
+ """Regex find & replace. Missing from python-shortcuts; this is the
30
+ standard serialization Shortcuts expects."""
31
+
32
+ itype = "is.workflow.actions.text.replace"
33
+ keyword = "replace_text"
34
+
35
+ find = Field("WFReplaceTextFind")
36
+ replace = Field("WFReplaceTextReplace", required=False)
37
+ case_sensitive = BooleanField("WFReplaceTextCaseSensitive", required=False)
38
+ regex = BooleanField("WFReplaceTextRegularExpression", required=False)
39
+
40
+
41
+ def rep(find: str, replace: str) -> ReplaceTextAction:
42
+ return ReplaceTextAction(
43
+ data={"find": find, "replace": replace, "case_sensitive": False, "regex": True}
44
+ )
45
+
46
+
47
+ def build(name: str, actions: list, out_path: str) -> None:
48
+ # plistlib.Data was removed in Python 3.12 and breaks the library's
49
+ # default icon dump; we set the icon in post-processing anyway.
50
+ Shortcut._get_icon = lambda self: {
51
+ "WFWorkflowIconStartColor": 4282601983,
52
+ "WFWorkflowIconGlyphNumber": 61440,
53
+ }
54
+
55
+ sc = Shortcut(name=name)
56
+ sc.actions = actions
57
+ with open(out_path, "wb") as f:
58
+ sc.dump(f, file_format="shortcut")
59
+
60
+ with open(out_path, "rb") as f:
61
+ data = plistlib.load(f)
62
+
63
+ # Share Sheet availability + accepted input types.
64
+ data["WFWorkflowTypes"] = ["ActionExtension"]
65
+ data["WFWorkflowInputContentItemClasses"] = [
66
+ "WFURLContentItem",
67
+ "WFTextContentItem",
68
+ "WFWebPageContentItem",
69
+ "WFSafariWebPageContentItem",
70
+ ]
71
+ data["WFWorkflowIcon"] = {
72
+ "WFWorkflowIconStartColor": 4282601983,
73
+ "WFWorkflowIconEndColor": 4282601983,
74
+ "WFWorkflowIconGlyphNumber": 61440,
75
+ }
76
+ with open(out_path, "wb") as f:
77
+ plistlib.dump(data, f, fmt=plistlib.FMT_BINARY)
78
+
79
+ # Verify what we actually wrote.
80
+ with open(out_path, "rb") as f:
81
+ check = plistlib.load(f)
82
+ print(f"{out_path}: {len(check['WFWorkflowActions'])} actions")
83
+ for a in check["WFWorkflowActions"]:
84
+ print(" -", a["WFWorkflowActionIdentifier"])
85
+
86
+
87
+ if __name__ == "__main__":
88
+ name = sys.argv[1] if len(sys.argv) > 1 else "My Shortcut"
89
+ build(
90
+ name,
91
+ actions=[
92
+ CommentAction(data={"text": "Built with the apple-shortcuts-authoring skill."}),
93
+ ExpandURLAction(),
94
+ URLDecodeAction(),
95
+ rep(r"example-pattern", "replacement"),
96
+ URLEncodeAction(),
97
+ SetVariableAction(data={"name": "result"}),
98
+ TextAction(data={"text": "https://example.com/?q={{result}}"}),
99
+ OpenURLAction(),
100
+ ],
101
+ out_path=f"{name}.shortcut",
102
+ )